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:\project\da-tool\.idea D:\project\da-tool\da-tool.iml D:\project\da-tool\defaultProp.properties D:\project\da-tool\pom.xml D:\project\da-tool\src D:\project\da-tool\target D:\project\da-tool\userProp.properties 排序后: D:\project\da-tool\da-tool.iml D:\project\da-tool\defaultProp.properties D:\project\da-tool\pom.xml D:\project\da-tool\userProp.properties D:\project\da-tool\.idea D:\project\da-tool\src D:\project\da-tool\target Process finished with exit code 0
时间: 2024-10-28 22:03:19