java操作文件,生成文件,读取文件,按顺序读取文件

按顺序读取文件名

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 name
        Arrays.sort(files, (f1, f2) -> f2.getName().compareTo(f1.getName()));

        // Print sorted file names
        for (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 name
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return f2.getName().compareTo(f1.getName());
            }
        });

        // Print sorted file names
        for (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();
}

你可能感兴趣的:(java,python,算法)