티스토리 뷰

git source 소스 링크

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.time.LocalDateTime;

public class FileObserver {

    public static void main(String[] args) {

        String targetDirectory = "D:\\";
        observeFileCreated(targetDirectory);

    }

    private static void observeFileCreated(String targetDirectory) {


        Path faxFolder = Paths.get(targetDirectory);

        try {

            WatchService fileWatchService = FileSystems.getDefault().newWatchService();
            faxFolder.register(fileWatchService, StandardWatchEventKinds.ENTRY_CREATE);

            boolean valid = true;
            do {
                WatchKey watchKey = fileWatchService.take();

                for (WatchEvent event : watchKey.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
                        String fileName = event.context().toString();
                        System.out.println("start to notify file Created :" + fileName + " , time : " + LocalDateTime.now());
                    }
                }
                valid = watchKey.reset();

            } while (valid);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


}

결과

D드라이브에 폴더가 만들어 졌을때

start to notify file Created :새 폴더 , time : 2020-07-03T17:56:38.133

D드라이브에 파일이 만들어졌을때

start to notify file Created :새 텍스트문서 , time : 2020-07-03T17:56:44.964

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함