Here you can find the source of deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories)
Parameter | Description |
---|---|
directoryPath | Path of directory whose contents to delete |
deleteChildDirectories | True to recursively delete all directories |
Parameter | Description |
---|---|
Exception | an exception |
public static boolean deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories) throws Exception
//package com.java2s; import java.io.File; public class Main { /**/*from w ww . j ava2s . c o m*/ * Delete a directories contents. If deleteChildDirectories is true, then recursively * delete all child directories also, otherwise just delete the files. * * @param directoryPath Path of directory whose contents to delete * @param deleteChildDirectories True to recursively delete all directories * @throws Exception */ public static boolean deleteDirectoryContents(String directoryPath, boolean deleteChildDirectories) throws Exception { final String eLabel = "FileUtils.deleteDirectoryContents: "; try { File directory = new File(directoryPath); if (!directory.exists()) { return false; } if (!directory.isDirectory()) { throw new Exception("Not a directory!!!"); } File[] children = directory.listFiles(); for (int i = 0; i < children.length; i++) { if (children[i].isFile()) { if (!children[i].delete()) { throw new Exception("Could not delete file: " + children[i].getName()); } } else { if (deleteChildDirectories) { deleteDirectoryContents(children[i].getPath(), true); } if (!children[i].delete()) { throw new Exception("Could not delete directory: " + children[i].getName()); } } } return true; } catch (Exception e) { throw new Exception(eLabel + e); } } }