0

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.

jogorm
  • 33
  • 1
  • 6
  • **How** doesn't it work? What do you expect this to do, and what does it do instead? What's the stack trace of the exception, if any? – JB Nizet Feb 28 '15 at 14:20
  • Sorry, probably should have added that. It finds the first out of three ds_stores, and prints out that it has been deleted, but the file is still there. None of the empty folders(containing ds_store) gets deleted. I get no errors. – jogorm Feb 28 '15 at 14:23

0 Answers0