1. 程式人生 > >android同一資料夾的檔案按時間、檔案大小、名稱排序

android同一資料夾的檔案按時間、檔案大小、名稱排序

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