Here you can find the source of deleteDirectoryTree(String directoryPath)
Parameter | Description |
---|---|
directoryPath | the directory to delete the contents of |
public static void deleteDirectoryTree(String directoryPath) throws Exception
//package com.java2s; /*//from w w w .j a va 2s. c om * Copyright (c) 2003-2010 The Regents of the University of California. * All rights reserved. * * '$Author: crawl $' * '$Date: 2013-02-21 11:20:05 -0800 (Thu, 21 Feb 2013) $' * '$Revision: 31474 $' * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the above * copyright notice and the following two paragraphs appear in all copies * of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * */ import java.io.File; import java.util.Vector; public class Main { /** * deletes a directory tree, not including the child of directoryPath. if * directoryPath == "/temp/cache" all of the contents of 'cache' will be * deleted but not 'cache' itself * * @param directoryPath * the directory to delete the contents of */ public static void deleteDirectoryTree(String directoryPath) throws Exception { long length = 0; File root = new File(directoryPath); if (!root.isDirectory()) { throw new Exception("The path " + root.getAbsolutePath() + " specified is not a directory"); } if (!root.exists()) { throw new Exception("The path " + root.getAbsolutePath() + " does not exist."); } if (!root.canWrite()) { throw new Exception("Invalid write permissions on the path " + root.getAbsolutePath()); } String[] listing = root.list(); Vector dirs = new Vector(); // delete the files for (int i = 0; i < listing.length; i++) { File f = new File(directoryPath + "/" + listing[i]); if (f.isFile()) { if (!f.delete()) { throw new Exception("Could not delete " + f.getAbsolutePath()); } } else if (f.isDirectory()) { dirs.addElement(f); } } // recurse into each directory for (int i = 0; i < dirs.size(); i++) { File f = (File) dirs.elementAt(i); deleteDirectoryTree(f.getAbsolutePath()); if (!f.delete()) { // delete this directory throw new Exception("Could not delete " + f.getAbsolutePath()); } } } }