I am trying to delete empty folders in java, here is my code:
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path file : stream) {
if (file.toFile().isFile()) {
System.out.println("Path is File");
System.out.println("Filename: " + file.toString());
if(file.toString().contains("DS_Store")){
Files.delete(file);
System.out.println("DS_Store file deleted");
}
}
if (file.toFile().isDirectory()) {
if (file.toFile().list().length > 0) {
System.out.println("Folder is not empty");
System.out.println("File length: " + file.toFile().list().length);
} else {
removeEmptyFolder(file);
Files.delete(file);
System.out.println("Deleting empty folder");
}
}
}
} catch (IOException ex) {
Logger.getLogger(jpegData.class.getName()).log(Level.SEVERE, null, ex);
System.err.println("IOException in removeEmptyFolder");
}
It doesn't really work, and I suspect that hidden files are the reason. I am doing a check for "DS_Store" files, but it doesn't really seem to work. Any tips? This code can probably be shorter as well.
EDIT: Forgot to mention the outcome of the code. The console will print "DS_Store file deleted", but it's either being created again automatically, or Files.delete(file) does not work. Furthermore it only finds on out of three DS_Store files. No errors are given, no folders are deleted.