无限循环检测最新文件

时间:2018-11-16 12:22:54

标签: java file

我需要运行一个无限循环,该循环显示一个新创建的文件的名称,其中在存储库中检测到一个新文件,然后将其停止,直到创建一个新文件为止。

        String directoryPath = "/home/Maria/Bureau/file/"; 
        File directory = new File(directoryPath); 

        File moreRecentFile = null; 
        File[] subfiles = directory.listFiles(); 
        if( subfiles.length > 0 )
        {
            moreRecentFile = subfiles[0]; 

        for (int i = 1; i < subfiles.length; i++) 

        { 
            File subfile = subfiles[i]; 

        if (subfile.lastModified() > moreRecentFile.lastModified())
            moreRecentFile = subfile;
        }

        System.out.println(moreRecentFile.getName()); 

        }

我写了这段代码来检测新创建的文件,我想知道如何添加这个循环。

1 个答案:

答案 0 :(得分:0)

现代操作系统和文件系统AFAIK支持所谓的文件系统事件,您可以在其中创建侦听器并接收有关文件系统更改的事件,包括新文件创建事件。

F.e。来自Oracle文档:https://docs.oracle.com/javase/tutorial/essential/io/notification.html

for (;;) {

    // wait for key to be signaled
    WatchKey key;
    try {
        key = watcher.take();
    } catch (InterruptedException x) {
        return;
    }

    for (WatchEvent<?> event: key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();

        // This key is registered only
        // for ENTRY_CREATE events,
        // but an OVERFLOW event can
        // occur regardless if events
        // are lost or discarded.
        if (kind == OVERFLOW) {
            continue;
        }

        // The filename is the
        // context of the event.
        WatchEvent<Path> ev = (WatchEvent<Path>)event;
        Path filename = ev.context();

        // Verify that the new
        //  file is a text file.
        try {
            // Resolve the filename against the directory.
            // If the filename is "test" and the directory is "foo",
            // the resolved name is "test/foo".
            Path child = dir.resolve(filename);
            if (!Files.probeContentType(child).equals("text/plain")) {
                System.err.format("New file '%s'" +
                    " is not a plain text file.%n", filename);
                continue;
            }
        } catch (IOException x) {
            System.err.println(x);
            continue;
        }

        // Email the file to the
        //  specified email alias.
        System.out.format("Emailing file %s%n", filename);
        //Details left to reader....
    }

    // Reset the key -- this step is critical if you want to
    // receive further watch events.  If the key is no longer valid,
    // the directory is inaccessible so exit the loop.
    boolean valid = key.reset();
    if (!valid) {
        break;
    }
}

另一个很好的示例链接:https://www.baeldung.com/java-nio2-watchservice