Sort by file name:
public static void orderByName(String filePath) {
File file = new File(filePath);
File[] files = file.listFiles();
List<File> fileList = Arrays.asList(files);
fileList.sort(new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if (o1.isDirectory() && o2.isFile()) {
return -1;
}
if (o1.isFile() && o2.isDirectory()) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
for (File file1 : files) {
System.out.println(file1.getName());
}
}
Sort by file modification date:
public static void orderByDate(String filePath) {
File file = new File(filePath);
File[] files = file.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = f1.lastModified() - f2.lastModified();
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
return -1;//如果 if 中修改为 返回-1 同时此处修改为返回 1 排序就会是递减
}
});
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
System.out.println(new Date(files[i].lastModified()));
}
}
Sort by file size:
public static void orderByLength(String filePath) {
File file = new File(filePath);
File[] files = file.listFiles();
List<File> fileList = Arrays.asList(files);
fileList.sort((f1, f2) -> {
//这里可以使用lambda表达式
long diff = f1.length() - f2.length();
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
return -1;//如果 if 中修改为 返回-1 同时此处修改为返回 1 排序就会是递减
});
for (File file1 : files) {
if (file1.isDirectory()) continue;
System.out.println(file1.getName() + ":" + file1.length());
}
}
Comparator uses the strategy model, defines a series of algorithms, encapsulates them one by one, and makes them interchangeable.
There are many different strategies for implementing the Comparator interface. Name, date, and file size are strategies.