Search code examples
javafilefileutils

Deleting Empty directory in java


Scenario:

Path: /users/country/CAN/DateFolder1 more directories /users/country/CAN/DateFolder2 /users/country/CAN/DateFolder3

DateFolder1 and DateFolder2 are empty.

I want to delete datefolder when they are empty, but i can't mention the datefolder name exclusively

using below, i am able to delete directory till the path i mention, but need logic to search. for inner directories only after the specified path.

FileSystemUtils.deleteRecursively(Paths.get("/Users/country/CAN/"));


Solution

  • To delete empty folders inside /users/country/CAN without recurcy:

    File dataFolder = new File("/users/country/CAN");
    File[] dataFolderContent = dataFolder.listFiles();
    if (dataFolderContent != null && dataFolderContent.length > 0) {
        for (File item : dataFolderContent) {
            if (item.isDirectory()) {
                File[] itemContent = item.listFiles();
                if (itemContent != null && itemContent.length == 0) {
                    item.delete();
                }
            }
        }
    }
    

    Update. For example root folder is /users/country and we need to remove all empty folders at a certain depth from root. In case from your comment depth=2. I used most simple IO as task is simple. If you want NIO you can find about Files.walk(Path path, int depth).

    public void deleteEmpty(File folder, int depth) {
        if (folder.isDirectory()) {
            if (depth == 0) {
                String[] folderContent = folder.list();
                if (folderContent != null && folderContent.length == 0) {
                    folder.delete();
                }
            } else {
                depth--;
                File[] listFiles = folder.listFiles();
                if (listFiles != null && listFiles.length > 0) {
                    for (File file : listFiles) {
                        deleteEmpty(file, depth);
                    }
                }
            }
        }
    }
    

    Update 2. Example with NIO.

    final int targetDepth = 2;
    final Path path = Paths.get("/users/country");
    try (Stream<Path> walk = Files.walk(path, targetDepth)) {
        walk.filter(Files::isDirectory).forEach(folderPath -> {
            if ((folderPath.getNameCount() - path.getNameCount()) == targetDepth) {
                File folder = folderPath.toFile();
                String[] list = folder.list();
                if (list != null && list.length == 0) {
                    folder.delete();
                }
            }
        });
    }