Reputation: 2604
i want to retrieve a list of files from a folder and everytime a new file is added, it should be listed instantly.
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path filee: stream) {
System.out.println(filee.getFileName());
}
Upvotes: 1
Views: 238
Reputation: 41935
import static java.nio.file.StandardWatchEventKinds.*;
Path dir = ...;
try {
WatchKey key = dir.register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY);
} catch (IOException x) {
System.err.println(x);
}
public class Main {
public static void main(String[] args) {
//define a folder root
Path myDir = Paths.get("D:/data");
try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,
StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
}
Upvotes: 0
Reputation: 2426
For this better you can use file system watcher in java. This file system watcher can watch the particular directory and intimate any modification may occur in that directory, like creation of files and deletion etc. This link may usefull for you. file system watcher in java
Upvotes: 1