按顺序读取文件名
Arrays.sort()`方法对文件数组进行排序,然后按照排序后的顺序遍历文件数组,以按照文件名从大到小的顺序展示文件名
public class FileSortExample {public static void main(String[] args) {File directory = new File("path/to/directory");File[] files = directory.listFiles();// Sort files in descending order by nameArrays.sort(files, (f1, f2) -> f2.getName().compareTo(f1.getName()));// Print sorted file namesfor (File file : files) {System.out.println(file.getName());}}
}
2按顺序
public class FileSortExample {public static void main(String[] args) {File directory = new File("path/to/directory");File[] files = directory.listFiles();// Sort files in descending order by nameArrays.sort(files, new Comparator<File>() {@Overridepublic int compare(File f1, File f2) {return f2.getName().compareTo(f1.getName());}});// Print sorted file namesfor (File file : files) {System.out.println(file.getName());}}
}
创建文件夹
File folder = new File("path/to/folder");
if (!folder.exists()) {boolean success = folder.mkdirs();if (success) {System.out.println("Folder created successfully!");} else {System.out.println("Failed to create folder!");}
} else {System.out.println("Folder already exists!");
}
删除文件
if (file.exists()) {file.delete();}
创建文件
if (!file.exists()) {// 逐级创建文件夹file.mkdirs();
}