java 删除文件夹中的所有文件及文件夹

删除文件夹(前提:文件夹为空以及InputStream和OutputStream等一些数据文件流关掉【close()】,否则文件无法删除)

  1. //删除文件夹  
  2. public static void delFolder(String folderPath) {  
  3.      try {  
  4.         delAllFile(folderPath); //删除完里面所有内容  
  5.         String filePath = folderPath;  
  6.         filePath = filePath.toString();  
  7.         java.io.File myFilePath = new java.io.File(filePath);  
  8.         myFilePath.delete(); //删除空文件夹  
  9.      } catch (Exception e) {  
  10.        e.printStackTrace();   
  11.      }  
  12. }  

删除指定文件夹下的所有文件

  1. public static boolean delAllFile(String path) {  
  2.        boolean flag = false;  
  3.        File file = new File(path);  
  4.        if (!file.exists()) {  
  5.          return flag;  
  6.        }  
  7.        if (!file.isDirectory()) {  
  8.          return flag;  
  9.        }  
  10.        String[] tempList = file.list();  
  11.        File temp = null;  
  12.        for (int i = 0; i < tempList.length; i++) {  
  13.           if (path.endsWith(File.separator)) {  
  14.              temp = new File(path + tempList[i]);  
  15.           } else {  
  16.               temp = new File(path + File.separator + tempList[i]);  
  17.           }  
  18.           if (temp.isFile()) {  
  19.              temp.delete();  
  20.           }  
  21.           if (temp.isDirectory()) {  
  22.              delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件  
  23.              delFolder(path + "/" + tempList[i]);//再删除空文件夹  
  24.              flag = true;  
  25.           }  
  26.        }  
  27.        return flag;  
  28.      }  
  29. }  
posted @ 2017-08-30 17:55  lucktian  阅读(32453)  评论(0编辑  收藏  举报