删除文件夹工具类 DeleteFolder.java

  1. package com.util;  
  2.   
  3. import java.io.File;  
  4.   
  5. /** 
  6.  * 删除文件夹 
  7.  * @createTime DSC 20, 2010 15:38 
  8.  * @version 2.0 
  9.  */  
  10. public class DeleteFolder {  
  11.     // 删除文件夹  
  12.     // param folderPath 文件夹完整绝对路径  
  13.     public static void delFolder(String folderPath) {  
  14.         try {  
  15.             delAllFile(folderPath); // 删除完里面所有内容  
  16.             String filePath = folderPath;  
  17.             filePath = filePath.toString();  
  18.             java.io.File myFilePath = new java.io.File(filePath);  
  19.             myFilePath.delete(); // 删除空文件夹  
  20.         } catch (Exception e) {  
  21.             e.printStackTrace();  
  22.         }  
  23.     }  
  24.   
  25.     // 删除指定文件夹下所有文件  
  26.     // param path 文件夹完整绝对路径  
  27.     public static boolean delAllFile(String path) {  
  28.         boolean flag = false;  
  29.         File file = new File(path);  
  30.         if (!file.exists()) {  
  31.             return flag;  
  32.         }  
  33.         if (!file.isDirectory()) {  
  34.             return flag;  
  35.         }  
  36.         String[] tempList = file.list();  
  37.         File temp = null;  
  38.         for (int i = 0; i < tempList.length; i++) {  
  39.             if (path.endsWith(File.separator)) {  
  40.                 temp = new File(path + tempList[i]);  
  41.             } else {  
  42.                 temp = new File(path + File.separator + tempList[i]);  
  43.             }  
  44.             if (temp.isFile()) {  
  45.                 temp.delete();  
  46.             }  
  47.             if (temp.isDirectory()) {  
  48.                 delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
  49.                 delFolder(path + "/" + tempList[i]);// 再删除空文件夹  
  50.                 flag = true;  
  51.             }  
  52.         }  
  53.         return flag;  
  54.     }  
  55.   
  56. }  
原文地址:https://www.cnblogs.com/swite/p/5168714.html