Wednesday, July 8, 2009

How to delete recursively empty folder using java, Recursively Delete Empty Folders

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DeleteEmptyFolder {
public static void main(String[] args) throws IOException {
deleteEmptyFolders("C:\\temp");
}

public static void deleteEmptyFolders(String folderName) throws FileNotFoundException {
File aStartingDir = new File(folderName);
List<File> emptyFolders = new ArrayList<File>();
findEmptyFoldersInDir(aStartingDir, emptyFolders);
List<String> fileNames = new ArrayList<String>();
for (File f : emptyFolders) {
String s = f.getAbsolutePath(); fileNames.add(s);
}
for (File f : emptyFolders) {
boolean isDeleted = f.delete();
if (isDeleted) {
System.out.println(f.getPath() + " deleted");
}
}
}

public static boolean findEmptyFoldersInDir(File folder, List<File> emptyFolders) {
boolean isEmpty = false;
File[] filesAndDirs = folder.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
if (filesDirs.size() == 0) { isEmpty = true; }
if (filesDirs.size() > 0) {
boolean allDirsEmpty = true;
boolean noFiles = true;
for (File file : filesDirs) {
if (!file.isFile()) {
boolean isEmptyChild = findEmptyFoldersInDir(file, emptyFolders);
if (!isEmptyChild) { allDirsEmpty = false; }
}
if (file.isFile()) { noFiles = false; }
}
if (noFiles == true && allDirsEmpty == true) { isEmpty = true; }
} if (isEmpty) { emptyFolders.add(folder); }
return isEmpty;
}
}

3 comments:

  1. Hi Binod Suman,

    This is Shrikant, just now read your comment on ‘Apache CouchDB and Java’ on
    http://www.drdobbs.com/ website.
    By reading the comment I thought you executed the java program successfully related to creating Employee database in CouchDB and subsequently adding and deleting the documents. So I just wanted the source code of that particular program urgently as I am not able to execute it completely.
    I will be grateful to you if you send me the source code to my mail id shrikant.katagi@gmail.com

    Thanking you in advance,
    Shrikant

    ReplyDelete
  2. How to delete recursively ...
    great work buddy, u save my lot of time
    Thanks !!

    ReplyDelete
  3. Thanks buddy u save my lot of time,,
    Great work !!

    ReplyDelete

You can put your comments here (Either feedback or your Question related to blog)