Java刪除目錄實例
如何刪除目錄?
解決方法
下麵的例子如何通過使用File類的dir.isDirectory(),dir.list()和deleteDir()方法刪除文件後刪除目錄。
import java.io.File; public class Main { public static void main(String[] argv) throws Exception { deleteDir(new File("c:\temp")); } public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir (new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); System.out.println("The directory is deleted."); } }
結果
上麵的代碼示例將產生以下結果。
The directory is deleted.