Here you can find the source of deleteDir(File dir)
Parameter | Description |
---|---|
dir | The directory. |
Parameter | Description |
---|---|
IOException | If something cannot be deleted. |
public static void deleteDir(File dir) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.IOException; public class Main { private static final File[] EMPTY_FILE_ARRAY = new File[0]; /**//from ww w. j a v a 2 s. c o m * Delete a directory and all of its contents. * * @param dir * The directory. * @throws IOException * If something cannot be deleted. */ public static void deleteDir(File dir) throws IOException { if (!dir.exists()) { return; } File[] files = listFiles(dir); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { deleteDir(file); } else { deleteFile(file); } } dir.delete(); } /** * Utility method to list files but return an empty array instead of null for no results. * * @param dir * The directory. * @return The array of files. */ public static File[] listFiles(File dir) { File[] files = dir.listFiles(); if (files == null) { files = EMPTY_FILE_ARRAY; } return files; } /** * Delete file. * * @param file * The file. * @throws IOException * If the file was not deleted. */ private static void deleteFile(File file) throws IOException { boolean success = file.delete(); if (!success) { throw new IOException("Could not delete " + file); } } /** * Delete a file or directory. * * @param file * The file or directory. * @throws IOException * For IO Errors. */ public static void delete(File file) throws IOException { if (file.isDirectory()) { deleteDir(file); } else { deleteFile(file); } } }