获取文件夹或文件的大小

新手上路,请多包涵

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

原文由 oneat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 655
2 个回答
java.io.File file = new java.io.File("myfile.txt");
file.length();

这将返回文件的字节长度或 0 如果文件不存在。没有获取文件夹大小的内置方法,您将不得不递归地遍历目录树(使用代表目录的文件对象的 listFiles() 方法)并累积目录适合自己的尺码:

 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() 可能返回 null 并导致 NullPointerException 。此外,它不考虑符号链接并且可能有其他故障模式。使用 此方法

原文由 Tendayi Mawushe 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 Aksel Willgert 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题