获取最新文件

时间:2016-07-08 19:57:04

标签: java file nio

使用

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

我的DirectoryStream中的dir个文件与pattern匹配。但我对所有这些文件都不感兴趣。我只想获得最新的文件,我知道最新版本的文件名是按字典顺序排列的最大文件名(因为包含了时间戳)。获取此文件的最简单方法是什么?它始终是我流中最后一个吗?你会做什么?

2 个答案:

答案 0 :(得分:1)

你好,这是一个我认为正在做你需要的代码片段。

        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中可以提出的最好的方法。

答案 1 :(得分:1)

我将争辩说,由于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()));
    }
}

使用第一个参数(比如说).txt和第二个参数/tmp/files正确打印最新的.*txt文件(注意:它是正则表达式,而不是glob)。

found: 6.txt

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