java 刪除檔案夾中的所有檔案及檔案夾

來源:互聯網
上載者:User

標籤:public   tostring   ati   catch   inpu   null   art   檔案流   length   

刪除檔案夾(前提:檔案夾為空白以及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. }  

java 刪除檔案夾中的所有檔案及檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.