Created
October 16, 2013 13:55
-
-
Save karmanov/7008142 to your computer and use it in GitHub Desktop.
Monitor a Folder using Java
This file contains 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
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; | |
public class App04 { | |
public static void main(String[] args) throws IOException, | |
InterruptedException { | |
Path postFolder = Paths.get("D:\\test"); | |
WatchService watchService = FileSystems.getDefault().newWatchService(); | |
postFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); | |
boolean valid = true; | |
do { | |
WatchKey watchKey = watchService.take(); | |
for (WatchEvent<?> event : watchKey.pollEvents()) { | |
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) { | |
String fileName = event.context().toString(); | |
System.out.println("File Created: " + fileName); | |
} | |
if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { | |
String fileName = event.context().toString(); | |
System.out.println("File Modified: " + fileName); | |
} | |
if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) { | |
String fileName = event.context().toString(); | |
System.out.println("File Deleted: " + fileName); | |
} | |
} | |
valid = watchKey.reset(); | |
} while (valid); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment