Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort files in a directory in java?

Tags:

java

file

sorting

Here is my code and it works ! But I want to be able to sort the files list according to name, size, modification date and more

import java.io.File;
import org.apache.commons.io.FileUtils;

public class StartingPoint {
    public static void main(String[] args) {
        File file = new File(
                "/home/t/lectures");
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println("File : " + f.getName() + " ["
                    + FileUtils.byteCountToDisplaySize(f.length()) + "]");
        }
    }
}
like image 750
taabouzeid Avatar asked Nov 12 '11 19:11

taabouzeid


2 Answers

Arrays.sort( files, new Comparator<File>() {
    public int compare( File a, File b ) {
        // do your comparison here returning -1 if a is before b, 0 if same, 1 if a is after b
    }
} );

You could define a bunch of different Comparator classes to do different comparisons like such:

public class FileNameComparator implements Comparator<File> {
    public int compare( File a, File b ) {
        return a.getName().compareTo( b.getName() );
    }
}

public class FileSizeComparator implements Comparator<File> {
    public int compare( File a, File b ) {
        int aSize = a.getSize();
        int bSize = b.getSize();
        if ( aSize == bSize ) {
            return 0;
        }
        else {
            return Integer.compare(aSize, bSize);
        }
    }
}

...

Then you would just swap em out:

Arrays.sort( files, new FileNameComparator() );

or

Arrays.sort( files, new FileSizeComparator() );
like image 88
Lucas Avatar answered Oct 10 '22 07:10

Lucas


Example in Java8 to sort by last modification time:

Path dir = Paths.get("./path/somewhere");

Stream<Path> sortedList = Files.list(dir)
    .filter(f -> Files.isDirectory(f) == false) // exclude directories
    .sorted((f1, f2) -> (int) (f1.toFile().lastModified() - f2.toFile().lastModified()));

then you may convert sortedList to Array or continue using lambda expressions with .forEach:

    .forEach(f -> {do something with f (f is Path)}) 
like image 38
Almaz Avatar answered Oct 10 '22 07:10

Almaz