Sorting files by created date using FileUtils Apache

45 views Asked by At

Is there a way to sort files in a directory using FileUtils Apache? I wan't to sort the files by the date they are created...

I have tried the following code:

public String[] getPDFFiles (String dir) throws IOException {
        File myDir = new File(dir);
        
        Collection<File> files = FileUtils.listFiles(myDir, 
               new String[] {"pdf", "PDF"}, true);
        
1

There are 1 answers

0
Kamil Krzywański On

That's all you nedd :)

        files.sort((file1, file2) -> {
        try {
            BasicFileAttributes attr1 = Files.readAttributes(file1.toPath(), BasicFileAttributes.class);
            BasicFileAttributes attr2 = Files.readAttributes(file2.toPath(), BasicFileAttributes.class);
            return attr1.creationTime().compareTo(attr2.creationTime());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });