package com.da.tool.util; import java.io.File; import java.util.*; /** * 文件和目录排序 */ public class FileSort { public static void main(String[] args) { String path ="D:\project\da-tool"; File file = new File(path); List<File> files = Arrays.asList(file.listFiles()); //排序前 System.out.println("排序前:"); for (File file1 : files) { System.out.println(file1.getPath()); } Collections.sort(files, new Comparator<File>() { @Override public int compare(File file1, File file2) { if(file1.isDirectory() && file2.isFile()){ return 1; } else if(file1.isFile() && file2.isDirectory()){ return -1; }else{ return file1.getName().compareTo(file2.getName()); } } }); System.out.println("排序后:"); for (File file1 : files) { System.out.println(file1.getPath()); } } }
排序前: D:projectda-tool.idea D:projectda-toolda-tool.iml D:projectda-tooldefaultProp.properties D:projectda-toolpom.xml D:projectda-toolsrc D:projectda-tool arget D:projectda-tooluserProp.properties 排序后: D:projectda-toolda-tool.iml D:projectda-tooldefaultProp.properties D:projectda-toolpom.xml D:projectda-tooluserProp.properties D:projectda-tool.idea D:projectda-toolsrc D:projectda-tool arget Process finished with exit code 0