I'd like to write a function that deletes all empty folders, with the option to ignore certain file types (allowed file types are stored in the hashmap) and tell if it should look inside directories.
Calling:
HashMap<String, Boolean> allowedFileTypes = new HashMap<String, Boolean>();
allowedFileTypes.put("pdf", true);
deleteEmptyFolders("ABSOLUTE PATH", allowedFileTypes, true);
Function:
public static void deleteEmptyFolders(String folderPath, HashMap<String, Boolean> allowedFileTypes, boolean followDirectory) {
File targetFolder = new File(folderPath);
File[] allFiles = targetFolder.listFiles();
if (allFiles.length == 0)
targetFolder.delete();
else {
boolean importantFiles = false;
for (File file : allFiles) {
String fileType = "folder";
if (!file.isDirectory())
fileType = file.getName().substring(file.getName().lastIndexOf('.') + 1);
if (!importantFiles)
importantFiles = (allowedFileTypes.get(fileType) != null);
if (file.isDirectory() && followDirectory)
deleteEmptyFolders(file.getAbsolutePath(), allowedFileTypes, followDirectory);
}
// if there are no important files in the target folder
if (!importantFiles)
targetFolder.delete();
}
}
The problem is that nothing is happening, even though it looks through all folders till the end. Is this a good approach or am I missing something completely?
This piece of code recursively delete all the empty folders or directory:
public class DeleteEmptyDir {
private static final String FOLDER_LOCATION = "E:\\TEST";
private static boolean isFinished = false;
public static void main(String[] args) {
do {
isFinished = true;
replaceText(FOLDER_LOCATION);
} while (!isFinished);
}
private static void replaceText(String fileLocation) {
File folder = new File(fileLocation);
File[] listofFiles = folder.listFiles();
if (listofFiles.length == 0) {
System.out.println("Folder Name :: " + folder.getAbsolutePath() + " is deleted.");
folder.delete();
isFinished = false;
} else {
for (int j = 0; j < listofFiles.length; j++) {
File file = listofFiles[j];
if (file.isDirectory()) {
replaceText(file.getAbsolutePath());
}
}
}
}
}
You can use code to delete empty folders using Java.
public static long deleteFolder(String dir) {
File f = new File(dir);
String listFiles[] = f.list();
long totalSize = 0;
for (String file : listFiles) {
File folder = new File(dir + "/" + file);
if (folder.isDirectory()) {
totalSize += deleteFolder(folder.getAbsolutePath());
} else {
totalSize += folder.length();
}
}
if (totalSize ==0) {
f.delete();
}
return totalSize;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With