Here you can find the source of deleteEmptyDirs(File dir)
Parameter | Description |
---|---|
dir | the directory to clean |
Parameter | Description |
---|---|
IOException | if some files couldn't be deleted |
public static void deleteEmptyDirs(File dir) throws IOException
//package com.java2s; /*/*from ww w . j ava2s. co m*/ * RapidContext <http://www.rapidcontext.com/> * Copyright (c) 2007-2013 Per Cederberg. All rights reserved. * * This program is free software: you can redistribute it and/or * modify it under the terms of the BSD license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the RapidContext LICENSE for more details. */ import java.io.File; import java.io.IOException; public class Main { /** * Deletes all empty directories in a directory, but leaves the * directory itself unmodified. This method will remove any empty * directories recursively, making it possible to remove a tree * of empty directories. * * @param dir the directory to clean * * @throws IOException if some files couldn't be deleted * * @see #deleteFiles(File) */ public static void deleteEmptyDirs(File dir) throws IOException { File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteEmptyDirs(files[i]); File[] subfiles = files[i].listFiles(); if (subfiles == null || subfiles.length == 0) { delete(files[i]); } } } } } /** * Deletes a file or a directory. This function will delete all * files and sub-directories inside a directory recursively. * * @param file the file or directory to delete * * @throws IOException if some files couldn't be deleted * * @see #deleteFiles(File) */ public static void delete(File file) throws IOException { if (file != null && file.isDirectory()) { deleteFiles(file); } if (file != null && !file.delete()) { throw new IOException("failed to delete " + file); } } /** * Deletes all files in a directory, but leaving the directory * otherwise unmodified. This function will delete any * sub-directories recursively. * * @param dir the directory to clean * * @throws IOException if some files couldn't be deleted * * @see #delete(File) */ public static void deleteFiles(File dir) throws IOException { if (dir != null && dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { delete(files[i]); } } } } }