Android implements folder sorting based on name modification time and size
- 2021-10-15 11:34:10
- OfStack
This article example for everyone to share the Android implementation of folder sorting specific code, for your reference, the specific content is as follows
Based on name:
/**
* Sort by file name
* @param filePath
*/
public static ArrayList<String> orderByName(String filePath) {
ArrayList<String> FileNameList = new ArrayList<String>();
File file = new File(filePath);
File[] files = file.listFiles();
List fileList = Arrays.asList(files);
Collections.sort(fileList, 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) {
if (file1.isDirectory()) {
FileNameList.add(file1.getName());
}
}
return FileNameList;
}
Based on the last modification time:
/**
* Sort by file modification time
* @param filePath
*/
public static ArrayList<String> orderByDate(String filePath) {
ArrayList<String> FileNameList = new ArrayList<String>();
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 if Modify in to Return -1 At the same time, it is modified here to return 1 The sort will be decreasing
}
public boolean equals(Object obj) {
return true;
}
});
for (File file1 : files) {
if (file1.isDirectory()) {
FileNameList.add(file1.getName());
}
}
return FileNameList;
}
Based on size:
/**
* Sort by file size
* @param filePath
*/
public static ArrayList<String> orderBySize(String filePath) {
ArrayList<String> FileNameList = new ArrayList<String>();
File file = new File(filePath);
File[] files = file.listFiles();
List<File> fileList = Arrays.asList(files);
Collections.sort(fileList, new Comparator<File>() {
public int compare(File f1, File f2) {
long s1 = getFolderSize(f1);
long s2 = getFolderSize(f2);
long diff = s1 - s2;
if (diff > 0)
return 1;
else if (diff == 0)
return 0;
else
return -1;// If if Modify in to Return -1 At the same time, it is modified here to return 1 The sort will be decreasing
}
public boolean equals(Object obj) {
return true;
}
});
for (File file1 : files) {
if (file1.isDirectory()) {
FileNameList.add(file1.getName());
}
}
return FileNameList;
}
/**
* Get folder size
* @param file File Instances
* @return long
*/
public static long getFolderSize(File file) {
long size = 0;
try {
java.io.File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}