获取文件夹或文件的大小 [英] Get size of folder or file

查看:27
本文介绍了获取文件夹或文件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I retrieve size of folder or file in Java?

推荐答案

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

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

This returns the length of the file in bytes or 0 if the file does not exist. There is no built-in way to get the size of a folder, you are going to have to walk the directory tree recursively (using the listFiles() method of a file object that represents a directory) and accumulate the directory size for yourself:

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.此外,它不考虑符号链接,并且可能具有其他故障模式.使用这种方法.

WARNING: This method is not sufficiently robust for production use. directory.listFiles() may return null and cause a NullPointerException. Also, it doesn't consider symlinks and possibly has other failure modes. Use this method.

这篇关于获取文件夹或文件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆