如何监听并获取文件目录中的文件列表?

时间:2013-12-12 17:51:53

标签: java file directory

我想从文件夹中检索文件列表,每次添加新文件时,都应该立即列出。<​​/ p>

Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path filee: stream) {
         System.out.println(filee.getFileName());
    }

2 个答案:

答案 0 :(得分:1)

为此,您可以在java中使用文件系统观察程序。此文件系统观察程序可以查看特定目录,并且可以在该目录中进行任何修改,例如创建文件和删除等。此链接可能对您有用。 file system watcher in java

答案 1 :(得分:0)

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