简体   繁体   中英

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 . 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 :

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.

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. 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).

found: 6.txt

(The directory contains these files: 1 2 3.txt 5.txt 6.txt ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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