微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在java中删除空目录

如何解决在java中删除空目录

场景:

路径:/users/country/CAN/DateFolder1 更多目录 /用户/国家/CAN/DateFolder2 /users/country/CAN/DateFolder3

DateFolder1 和 DateFolder2 为空。

我想在日期文件夹为空时删除它们,但我不能专门提及日期文件名称

使用下面,我可以删除目录直到我提到的路径,但需要逻辑来搜索。仅用于指定路径之后的内部目录。

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

解决方法

不重复删除 /users/country/CAN 中的空文件夹:

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();
            }
        }
    }
}

更新。 例如根文件夹是/users/country,我们需要从根目录删除一定深度的所有空文件夹。如果您的评论深度= 2。 我使用了最简单的 IO,因为任务很简单。如果你想要 NIO,你可以找到关于 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);
                }
            }
        }
    }
}

更新 2. 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();
            }
        }
    });
}
,

更新:更新了以下答案以反映预期。

我也在考虑 Java NIO API,但已经有一个公认的答案, 不过这里有一个使用 Java NIO 的 API

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.stream.Stream;

class Scratch extends SimpleFileVisitor<Path> {
    private static final Path basePath = Paths.get("/tmp/1");
    public static void main(String[] args) throws IOException {
        Scratch scratch = new Scratch();
        Files.walkFileTree(basePath,scratch);
    }


    @Override
    public java.nio.file.FileVisitResult postVisitDirectory(java.nio.file.Path dir,java.io.IOException exc) throws java.io.IOException {
        return super.postVisitDirectory(dir,exc);
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) throws IOException {
        if(attrs.isDirectory() && isEmpty(dir)) {
            if(dir.getParent().equals(basePath)) {
                System.out.printf("skipped dir %s since it is a direct descendant of %s\n",dir,basePath);
                return FileVisitResult.CONTINUE;
            }
            Files.delete(dir);
            System.out.println("deleted dir = " + dir);
            return FileVisitResult.SKIP_SUBTREE;
        }

        return FileVisitResult.CONTINUE;
    }

    // https://www.baeldung.com/java-check-empty-directory
    public static boolean isEmpty(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            try (Stream<Path> entries = Files.list(path)) {
                return entries.findFirst().isEmpty();
            }
        }

        return false;
    }
}

之前:

Before Run

输出:

Output

之后:

After

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。