删除文件夹2以下的全部文件及其文件夹

演示样例文件夹例如以下:D:/test/1/2

1、使用FileUtils类。静默删除
        String url = "D:/test/1/2";
        boolean bol = FileUtils.deleteQuietly(new File(url));
        System.out.println(bol);

假设要删除文件夹1呢?
仅仅须要这样:

        String url = "D:/test/1/2";
        boolean bol = FileUtils.deleteQuietly(new File(url).getParentFile());
        System.out.println(bol);
2、使用File类操作
 public static void deleteDir(File file) {
        if (file.isDirectory()) {
            for (File f : file.listFiles())
                deleteDir(f);
        }
        file.delete();
    }

或者连当前的文件夹也一块删除。


比方:”D:/test/1/2” ,删除文件夹2以及该文件夹内的全部内容。

public static void deleteAll(File file) {

        if (file.isFile() || file.list().length == 0) {
            file.delete();
        } else {
            for (File f : file.listFiles()) {
                deleteAll(f); // 递归删除每个文件

            }
            file.delete(); // 删除文件夹
        }
    }

仅仅是删除了文件夹2以下的文件及其文件夹,假设连文件夹2也删掉也能够依照上述办法。

        String url = "D:/test/1/2";
        deleteDir(new File(url));

不论文件夹1和文件夹2之间是否还有其它文件或者文件夹都能够删掉!

相关文章:

  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
  • 2021-11-01
  • 2022-12-23
  • 2022-01-31
  • 2022-12-23
猜你喜欢
  • 2021-08-29
  • 2022-12-23
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
相关资源
相似解决方案