通过io流删除文件夹(包括文件夹下的所有文件)

io流在删除文件夹的时候,该文件夹里面必须没有文件,如果存在文件,则无法删除(window系统也是如此,window系统是通过递归的方式来先删除文件夹里面的文件,再删除该文件夹的方式来删除的!),所有必须通过程序先删除该文件夹里面的文件,再删除这个文件夹!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
public static boolean delAllFile(String path) {
  boolean flag = false;
  File file = new File(path);
  if (!file.exists()) {
    return flag;
  }
  if (!file.isDirectory()) {
    return flag;
  }
  String[] tempList = file.list();
  File temp = null;
  for (int i = 0; i < tempList.length; i++) {
    if (path.endsWith(File.separator)) {
      temp = new File(path + tempList[i]);
    } else {
      temp = new File(path + File.separator + tempList[i]);
    }
    if (temp.isFile()) {
      temp.delete();
    }
    if (temp.isDirectory()) {
      delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
      delFolder(path + "/" + tempList[i]);//再删除空文件夹
      flag = true;
    }
  }
  return flag;
}//删除文件夹
//param folderPath 文件夹完整绝对路径
public static void delFolder(String folderPath) {
  try {
    delAllFile(folderPath); //删除完里面所有内容
    String filePath = folderPath;
    filePath = filePath.toString();
    java.io.File myFilePath = new java.io.File(filePath);
    myFilePath.delete(); //删除空文件夹
  } catch (Exception e) {
    e.printStackTrace();
  }
}//调用方法测试<br>public void test(){
  String path = "C:/xx1/xx2";
  delFolder(path);//会把xx2下的所有文件包括xx2这个文件夹都删了
}

  

posted @   雪化山河  阅读(2304)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示