Here you can find the source of deleteDir(File dir)
Parameter | Description |
---|---|
dir | a parameter |
public static boolean deleteDir(File dir)
//package com.java2s; //License from project: Open Source License import java.io.*; public class Main { /**/*from w w w. j a v a 2 s. co m*/ * Deletes all files and subdirectories under dir. Returns true if all * deletions were successful. If a deletion fails, the method stops * attempting to delete and returns false. * * @param dir * @return True if success. */ 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; } } } // The directory is now empty so delete it return dir.delete(); } /** * returns true if fileName is a directory, otherwise false * * @param fileName * filename to check if it's a directory * @return true or false */ public static boolean isDirectory(String fileName) { boolean result = false; File tmpFile = new File(fileName); fileName = fileName.replace('/', File.separatorChar); String tmpPath = tmpFile.getAbsolutePath(); if (tmpPath.equalsIgnoreCase(fileName)) { result = true; } tmpPath = tmpFile.getPath(); if (tmpPath.equalsIgnoreCase(fileName)) { result = true; } tmpFile = null; tmpPath = null; return result; } /** * delete file * * @param fileName * file to delete * @return true if success, otherwise false */ public static boolean delete(String fileName) throws Exception { File f = new File(fileName); // Make sure the file or directory exists and isn't write protected if (!f.exists()) throw new IllegalArgumentException("Delete: no such file or directory: " + fileName); if (!f.canWrite()) throw new IllegalArgumentException("Delete: write protected: " + fileName); // If it is a directory, make sure it is empty if (f.isDirectory()) { String[] files = f.list(); if (files.length > 0) throw new IllegalArgumentException("Delete: directory not empty: " + fileName); } // Attempt to delete it boolean success = f.delete(); if (!success) throw new IllegalArgumentException("Delete: deletion of " + fileName + " failed"); f = null; return success; } }