Skip to content

Instantly share code, notes, and snippets.

@toboqus
Created January 4, 2016 08:18
Show Gist options
  • Save toboqus/88f0074478515d1d23e8 to your computer and use it in GitHub Desktop.
Save toboqus/88f0074478515d1d23e8 to your computer and use it in GitHub Desktop.
Deleting empty directories
import java.io.File;
public class Delete {
public static void main(String[] args) {
if(args.length != 1){
System.out.println("ERROR: A path must be specified.");
System.exit(0);
}else{
long start = System.nanoTime();
File directory = new File(args[0]);
deleteEmptyDirectories(directory);
long finish = System.nanoTime();
System.out.println("Execution time = " + (finish-start)/1000000f + " milliseconds ");
}
}
public static void deleteEmptyDirectories(File file){
if(file.isDirectory()){
if(file.list().length == 0){
file.delete();
System.out.println("Deleted directory: "+file.getAbsolutePath());
}else{
String[] files = file.list();
for(String temp: files){
File fileDelete = new File(file, temp);
deleteEmptyDirectories(fileDelete);
}
if(file.list().length == 0){
file.delete();
System.out.println("Deleted directory: "+file.getAbsolutePath());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment