Rashad.Z
Rashad.Z

Reputation: 2604

How to listen and get the list of files in a file directory?

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

Answers (2)

Narendra Pathai
Narendra Pathai

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);
}

I/O Notification in Java NIO

Watching for File system changes with Java 7

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

PS Kumar
PS Kumar

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

Related Questions