簡體   English   中英

獲取最新文件

[英]Get the most recent file

使用

DirectoryStream<Path> stream = Files.newDirectoryStream(dir,pattern);

我得到一個DirectoryStream在我的文件的dir匹配該pattern 但是我對所有這些文件都不感興趣。 我只想獲取最新的文件,並且我知道最新的文件名是按字典順序排列的最大文件名(因為包括了時間戳)。 獲取此文件的最簡單方法是什么? 它總是在我的視頻流中排在最后的嗎? 你會怎么做?

您好,這是一個代碼片段,我相信它可以滿足您的需求。

        DirectoryStream<Path> stream = Files.newDirectoryStream(dir,pattern);
        Path latestPath=null;
        FileTime latestTime = null;
        for (Path path:stream) {
            BasicFileAttributes attribs = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime time = attribs.creationTime();
            if (latestTime==null) {
                latestPath = path;
                latestTime = time;
            }
            else {
                if (time.compareTo(latestTime)>0) {
                    latestTime = time;
                    latestPath = path;
                }
            }
        }

Java 8版本:

DirectoryStream<Path> stream = Files.newDirectoryStream(null,"");
List<Path> list = new ArrayList()<>();
stream.forEach(list::add);
list.stream()
             .max((t,q)->{
                          BasicFileAttributes attribs1 = Files.readAttributes(t, BasicFileAttributes.class);
                          BasicFileAttributes attribs2 = Files.readAttributes(q, BasicFileAttributes.class);
                     return attribs1.creationTime().compareTo(attribs2.creationTime());});

我看不到任何可以直接從Iterator流式傳輸的方法,因此這是Java 8所能提供的最好的方法。

我要爭論的是,由於DirectoryStream並未真正提供Java 8流,因此回退到普通的舊File API可能會提供更直接的解決方案。 例如,以下程序:

public class MostRecentFile {
    public static void main(String[] args) throws IOException {
        Path dir = Paths.get(args[0]);
        String regex = args[1];
        Arrays.stream(dir.toFile().listFiles(fn -> fn.getName().matches(regex))).sorted((f1, f2) -> {
                    try {
                        FileTime c2 = Files.readAttributes(f2.toPath(),
                           BasicFileAttributes.class).creationTime();
                        FileTime c1 = Files.readAttributes(f1.toPath(),   
                           BasicFileAttributes.class).creationTime();
                        return c2.compareTo(c1);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            ).findFirst().ifPresent(f -> System.out.println("found: " + f.getName()));
    }
}

使用第一個參數(例如) /tmp/files和第二個參數.*txt (注意:這是一個正則表達式,而不是glob)正確打印最新的.txt文件。

found: 6.txt

(目錄包含以下文件: 1 2 3.txt 5.txt 6.txt )。

暫無
暫無

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

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