简体   繁体   English

获取最新文件

[英]Get the most recent file

Using 使用

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

I get a DirectoryStream of files in my dir which match pattern . 我得到一个DirectoryStream在我的文件的dir匹配该pattern But I'm not interested in all those files. 但是我对所有这些文件都不感兴趣。 I only want to get the most recent one and I know that the filename of the most recent one is the largest filename in terms of lexicographical order (because the timestamp is included). 我只想获取最新的文件,并且我知道最新的文件名是按字典顺序排列的最大文件名(因为包括了时间戳)。 What is the easiest way to get this file? 获取此文件的最简单方法是什么? Is it always the one which comes last in my stream? 它总是在我的视频流中排在最后的吗? What would you do? 你会怎么做?

Hello here is a code fragment that I believe is doing what you need. 您好,这是一个代码片段,我相信它可以满足您的需求。

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

I dont see any way we can stream straight from Iterator, so that is the best I can come up with when it comes to Java 8. 我看不到任何可以直接从Iterator流式传输的方法,因此这是Java 8所能提供的最好的方法。

I am going to argue that since DirectoryStream does not really provide a Java 8 stream, falling back to the plain old File API may provide a more straightforward solution. 我要争论的是,由于DirectoryStream并未真正提供Java 8流,因此回退到普通的旧File API可能会提供更直接的解决方案。 For instance, the following program: 例如,以下程序:

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

correctly prints the latest .txt file using first argument (say) /tmp/files and second argument .*txt (note: it is a regular expression, not a glob). 使用第一个参数(例如) /tmp/files和第二个参数.*txt (注意:这是一个正则表达式,而不是glob)正确打印最新的.txt文件。

found: 6.txt

(The directory contains these files: 1 2 3.txt 5.txt 6.txt ). (目录包含以下文件: 1 2 3.txt 5.txt 6.txt )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM