Created
August 14, 2019 15:12
-
-
Save horitaku1124/f63964233243dd9a0d7059c8b02b898a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.horitaku1124.java.event; | |
import java.io.IOException; | |
import java.nio.file.*; | |
import java.util.function.Consumer; | |
public class Eventer { | |
public static void getEvent(String filPath, Consumer<Path> callback) { | |
try { | |
Path filePath = Paths.get(filPath); | |
String fileName = filePath.getFileName().toString(); | |
Path parentDir = filePath.getParent(); | |
System.out.println("FileName: " + fileName); | |
// System.out.println("Parent: " + parentDir); | |
WatchService watchService = FileSystems.getDefault().newWatchService(); | |
parentDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, | |
StandardWatchEventKinds.ENTRY_DELETE, | |
StandardWatchEventKinds.ENTRY_MODIFY); | |
WatchKey key = watchService.take(); | |
while (true) { | |
for (WatchEvent<?> event : key.pollEvents()) { | |
WatchEvent.Kind<?> kind = event.kind(); | |
Object context = event.context(); | |
if (context instanceof Path) { | |
Path path = (Path)context; | |
String fileName2 = path.getFileName().toString(); | |
// System.out.println(kind); | |
// System.out.println("kind "+ kind.type().getName()); | |
// System.out.println(path.toAbsolutePath()); | |
// System.out.println(path.getFileName()); | |
if (fileName2.equals(fileName)) { | |
// System.out.println("catch"); | |
callback.accept(path); | |
} | |
} else { | |
System.err.println("context error"); | |
System.err.println(context); | |
} | |
} | |
} | |
} catch (IOException | InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment