folder文件夹下面的文件或者文件夹全部删掉

import java.io.File;

public class DeleteContents {
    public static void main(String[] args) {
        String folderPath = "C:/path/to/folder";
        File folder = new File(folderPath);

        deleteContents(folder);
        System.out.println("文件夹内容删除成功!");
    }

    public static void deleteContents(File folder) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteContents(file);
                    }
                    file.delete();
                }
            }
        }
    }
}

在上面的代码中,我们使用递归的方式遍历文件夹下的所有文件和文件夹。对于每一个文件夹,我们先递归调用deleteContents方法来删除其内部的文件和文件夹。然后,对于每一个文件或文件夹,我们直接调用delete方法来删除它们。
你只需将folderPath变量替换为实际的文件夹路径,并在需要的地方调用deleteContents方法即可实现删除文件夹下的所有内容的功能

posted @ 2024-01-16 08:44  我的心儿  阅读(49)  评论(0)    收藏  举报