Java/Android 獲取資料夾的檔案列表(file.listFiles())並按名稱排序,中文優先
阿新 • • 發佈:2018-12-07
排序規則
因為是中國人,習慣性看中文資料夾放前面比較順眼,所以在別人部落格(https://blog.csdn.net/da_caoyuan/article/details/56664673)的基礎上,加上了自己的排序規則。
預設排序規則是按照ASCII碼錶排序(http://ascii.911cha.com/),排序的步驟大概是:部分符號->數字->部分符號->大寫字母->部分符號->小寫字母->部分符號->中文。
所以我修改了邏輯,排序變成:中文->數字->字母(不區分大小寫)->特殊字元
演算法原理
1、將字串不區分大小寫
2、把字串中的中文變成拼音的首字母
3、識別字符串的第一個字元,如果是中文則在前面加上字元“.”,用於在compareTo方法中,排在數字前面
4、識別字符串的第一個字元,如果是符號(看ASCII表)則在前面加上字元“{”,用於在compareTo方法中,排在Z後面
程式碼
程式碼就不上註釋了,也比較簡單
File[] files = new File(path).listFiles(); List<File> list; if (files == null) { list = new ArrayList<>(); } else { list = Arrays.asList(files); } Collections.sort(list, 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; String name1 = o1.getName().toUpperCase(); char c1 = name1.toCharArray()[0]; String name11 = ""; for (char c11 : name1.toCharArray()) { name11 += Pinyin.toPinyin(c11); } if (c1 >= 0x4E00 && c1 <= 0x9FA5) { name1 = "." + name11; } else if (c1 < 48) { name1 = "{" + name11; } else if (c1 > 57 && c1 < 65) { name1 = "{" + name11; } String name2 = o2.getName().toUpperCase(); char c2 = name2.toCharArray()[0]; String name22 = ""; for (char c22 : name2.toCharArray()) { name22 += Pinyin.toPinyin(c22); } if (c2 >= 0x4E00 && c2 <= 0x9FA5) { name2 = "." + name22; } else if (c2 < 48) { name2 = "{" + name22; } else if (c2 > 57 && c2 < 65) { name2 = "{" + name22; } return name1.compareTo(name2); } });