获取文件夹或文件的大小

2022-08-31 09:05:13

如何在Java中检索文件夹或文件的大小?


答案 1
java.io.File file = new java.io.File("myfile.txt");
file.length();

这将返回文件的长度(以字节为单位),或者如果文件不存在,则返回文件的长度。没有内置的方法可以获得文件夹的大小,您将不得不以递归方式遍历目录树(使用表示目录的文件对象的方法)并为自己累积目录大小:0listFiles()

public static long folderSize(File directory) {
    long length = 0;
    for (File file : directory.listFiles()) {
        if (file.isFile())
            length += file.length();
        else
            length += folderSize(file);
    }
    return length;
}

警告:此方法对于生产用途来说不够可靠。 可能会返回并导致 .此外,它不考虑符号链接,并且可能具有其他故障模式。使用此方法directory.listFiles()nullNullPointerException


答案 2

使用java-7 nio api,计算文件夹大小可以更快完成。

下面是一个随时可以运行的示例,该示例是可靠的,不会引发异常。它将记录无法进入或无法遍历的目录。符号链接将被忽略,并且并发修改目录不会造成不必要的麻烦。

/**
 * Attempts to calculate the size of a file or directory.
 * 
 * <p>
 * Since the operation is non-atomic, the returned value may be inaccurate.
 * However, this method is quick and does its best.
 */
public static long size(Path path) {

    final AtomicLong size = new AtomicLong(0);

    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {

                size.addAndGet(attrs.size());
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) {

                System.out.println("skipped: " + file + " (" + exc + ")");
                // Skip folders that can't be traversed
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) {

                if (exc != null)
                    System.out.println("had trouble traversing: " + dir + " (" + exc + ")");
                // Ignore errors traversing a folder
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new AssertionError("walkFileTree will not throw IOException if the FileVisitor does not");
    }

    return size.get();
}

推荐