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. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM