1.文件按名字降序排列:
/**
* 将文件按名字降序排列
*/
class FileComparator implements Comparator<File> {
@Override
public int compare(File file1, File file2) {
return file2.getName().compareTo(file1.getName());
}
}
2.文件按时间降序排列:
/**
* 将文件按时间降序排列
*/
class FileComparator2 implements Comparator<File> {
@Override
public int compare(File file1, File file2) {
if (file1.lastModified() < file2.lastModified()) {
return 1;// 最后修改的文件在前
} else {
return -1;
}
}
}
3.文件按文件大小升序排列:
class FileComparator3 implements Comparator<File> {
@Override
public int compare(File file1, File file2) {
if (file1.length() < file2.length()) {
return -1;// 小文件在前
} else {
return 1;
}
}
}
4.调用方法:
List<File> fileList = new ArrayList<File>();
String path = FileUtils.IMAGE_PATH;//文件夹路径
File file = new File(path);
if (file.exists() && file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
fileList.add(files[i]);
}
Collections.sort(fileList, new FileComparator());
//Collections.sort(fileList, new FileComparator2());
//Collections.sort(fileList, new FileComparator3());