本文实例为大家分享了Android实现文件夹排序的具体代码,供大家参考,具体内容如下
基于名称:
/** * 按文件名排序 * @param filePath */ public static ArrayListorderByName(String filePath) { ArrayList FileNameList = new ArrayList (); File file = new File(filePath); File[] files = file.listFiles(); List fileList = Arrays.asList(files); Collections.sort(fileList, new Comparator () { @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; }
基于最近修改时间:
/** * 按文件修改时间排序 * @param filePath */ public static ArrayListorderByDate(String filePath) { ArrayList FileNameList = new ArrayList (); File file = new File(filePath); File[] files = file.listFiles(); Arrays.sort(files, new Comparator () { 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 排序就会是递减 } public boolean equals(Object obj) { return true; } }); for (File file1 : files) { if (file1.isDirectory()) { FileNameList.add(file1.getName()); } } return FileNameList; }
基于大小:
/** * 按文件大小排序 * @param filePath */ public static ArrayListorderBySize(String filePath) { ArrayList FileNameList = new ArrayList (); File file = new File(filePath); File[] files = file.listFiles(); List fileList = Arrays.asList(files); Collections.sort(fileList, new Comparator () { 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 中修改为 返回-1 同时此处修改为返回 1 排序就会是递减 } public boolean equals(Object obj) { return true; } }); for (File file1 : files) { if (file1.isDirectory()) { FileNameList.add(file1.getName()); } } return FileNameList; } /** * 获取文件夹大小 * @param file File实例 * @return long */ public static long getFolderSize(File file) { long size = 0; try { java.io.File[] fileList = file.listFiles(); for (int i = 0; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。