Get files in a directory sorted by last modified? [duplicate]

本小妞迷上赌 提交于 2019-12-18 03:09:24

问题


In Java 7 with the new I/O APIs, is there an easy way to list a directory's content by last modified date? Basically I only need to get the file the wasn't modified for the longest time (sort by last modified ascending, take first filename).


回答1:


There's no real "easy way" to do it, but it is possible:

List<Path> files = new ArrayList<>();
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for(Path p : stream) {
        files.add(p);
    }
}

Collections.sort(files, new Comparator<Path>() {
    public int compare(Path o1, Path o2) {
        try {
            return Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2));
        } catch (IOException e) {
            // handle exception
        }
    }
});

This will sort the files soonest modified files last. DirectoryStreams do not iterate through subdirectories.




回答2:


A slightly "stream"ier variation of the Jeffrey's answer, which some might find easier as well. Posting for completeness.

try (DirectoryStream<Path> files = Files.newDirectoryStream(path)) {
    StreamSupport.stream(files.spliterator(), false)
        .sorted((o1, o2) -> {
            try {
                return Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2));
            } catch (IOException ex) {
                ...
            }
        })
        .filter(file -> Files.isRegularFile(file))
        .forEach(file -> {
        });
}



回答3:


Use listFiles() on the directory's File object. Convert the array to an arraylist. Then sort them using a the static sort method on the Collections class with a custom Comparator that uses the getTotalSpace() method on the Files. EDIT: Use lastModified instead of getTotalSpace.




回答4:


lastModified()

Returns the time that the file denoted by this abstract pathname was last modified.

Java 7 - IO API




回答5:


you can use http://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html#listFiles(java.io.FileFilter) and supply http://docs.oracle.com/javase/1.5.0/docs/api/java/io/FileFilter.html

then compare http://docs.oracle.com/javase/1.5.0/docs/api/java/io/File.html#lastModified() and you're done

if you do care about performance - then simply take one with maximum/minimum value from the file list, that will give you O(n) complexity




回答6:


Note: This solution requires Guava.

Java IO/NIO API provides low-level access to directory listings, but there is no processing done, which is left to the caller. The new Java7 NIO DirectoryStream has the minimal footprint when accessing the directory listing for further processing, e.g. sorting.

Here is my solution: Read files from DirectoryStream and build a sorted queue with (optionally) limited size from the stream. Return the oldest/newest elements from the queue.

private void listFilesOldestFirst(final File directory, final Integer maxNumberOfFiles) {

    final Builder<File> builder =
            MinMaxPriorityQueue
            .orderedBy(LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
    if( maxNumberOfFiles != null ) {
        builder.maximumSize(maxNumberOfFiles);
    }

    // queue with constant space, if maxNumberOfFiles is set, otherwise behaves like an unbound queue with an O(log n) penalty for insertion
    final MinMaxPriorityQueue<File> oldestFiles = builder.create();

    try(DirectoryStream<Path> stream = Files.newDirectoryStream(directory.toPath())) {
        for(final Path p : stream) {
            oldestFiles.add(p.toFile());
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }

    final File[] fileArray = oldestFiles.toArray(new File[]{});
    Arrays.sort(fileArray, oldestFiles.comparator());
    // ... use fileArray

    final ArrayList<File> arrayList = Lists.newArrayList(oldestFiles);
    Collections.sort(arrayList, oldestFiles.comparator());
    // ... use arrayList

}

These dependencies are required for the Guava MinMaxPriorityQueue and the FileComparator:

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

You may also find the filter parameter of Files.newDirectoryStream useful:

    final Filter<Path> sampleFilter = new Filter<Path>() {
        @Override
        public boolean accept(final Path entry) throws IOException {
            return true; // see commons-io -> FileFilterUtils
        }
    };

    ...
    Files.newDirectoryStream(directory.toPath(), sampleFilter)


来源:https://stackoverflow.com/questions/12253908/get-files-in-a-directory-sorted-by-last-modified

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!