簡體   English   中英

如何列出特定目錄中所有新創建的文件?

[英]How to list all newly created files in a specific directory?

如何列出例如在兩個時間戳之間創建的文件的方式? 我想列出所有新創建的文件,然后將它們移到另一個目錄。

我在Windows上工作

public void afterDate() throws IOException {
    final String pathToDirectory = "/path/to/directory";
    final long afterDate = new Date().getTime();
    final List<Path> paths = new ArrayList<>();
    final Path directory = Paths.get(pathToDirectory);
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            final BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            final long creationTime = attr.creationTime().toMillis();
            if (creationTime >= afterDate) {
                paths.add(path);
            }
        }
    }
    for (final Path path : paths) {
        System.out.println(path.getFileName());
    }

}

如果您要實際監視新創建的文件,則可以使用WatchService: http ://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html

如果僅查找其中的文件,則可以使用例如Apache Commons FileUtils類的方法列出在兩個特定日期之間修改/創建的所有文件。

邏輯如下

使用文件類。

遍歷目錄中的所有文件

可以使用file.listFiles()方法完成。

該方法將返回目錄中的所有文件(文件以及目錄)。

然后對於每個文件對象,使用file.lastModified()獲取時間戳,然后檢查它是否在您指定的時間戳之間

startTimestamp <file.lastModified()<endTimestamp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM