如何在java中的目录中对文件进行排序?

时间:2011-11-12 19:34:19

标签: java file sorting

这是我的代码,它的工作原理!但我希望能够根据名称,大小,修改日期等对文件列表进行排序

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()) + "]");
        }
    }
}

2 个答案:

答案 0 :(得分:12)

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
    }
} );

您可以定义一堆不同的Comparator类来进行不同的比较:

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);
        }
    }
}

...

然后你就可以把它们换掉:

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

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

答案 1 :(得分:4)

Java8中按上次修改时间排序的示例:

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()));

然后你可以将sortedList转换为Array或继续使用带有.forEach的lambda表达式:

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