How can I sort files in a directory in java?

Here is my code and it works! But I want to be able to sort the list of files according to name, size, date modified, etc.

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()) + "]"); } } } 
+3
source share
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 can define a group of different Comparator classes to perform different comparisons, such as:

 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 just replace them:

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

or

 Arrays.sort( files, new FileSizeComparator() ); 
+11
source

An example in Java8 for sorting by time of the last modification:

 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 can convert sortedList to Array or continue using lambda expressions with .forEach:

  .forEach(f -> {do something with f (f is Path)}) 
+2
source

Source: https://habr.com/ru/post/1488456/


All Articles