Java获取磁盘目录大小

用File API可以获取指定目录的大小

freeSpace和usableSpace区别

FreeSpace:
Returns the number of unallocated bytes in the partition named by this abstract path name.
The returned number of unallocated bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.

UsableSpace:
Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace.
The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.

代码

    public static void main(String[] args) {
        File root = new File("/");
        System.out.println(root.getTotalSpace()); //500068036608
        System.out.println(root.getFreeSpace()); //44024229888
        System.out.println(root.getUsableSpace()); //30446862336

        System.out.println(readableFileSize(root.getTotalSpace())); //465.7 GB
        System.out.println(readableFileSize(root.getFreeSpace())); //41 GB
        System.out.println(readableFileSize(root.getUsableSpace())); //31.3 GB
    }

    /**
     * 格式化文件大小
     * 参考:https://stackoverflow.com/a/5599842/1253611
     *
     * @param size byte
     * @return readable file size
     */
    public static String readableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 今天注定是一個個錯誤的預算結成的障礙,為了提前取票在路上花了一個下午,東西沒有整理完,核對工資又排隊1個半小時,未完無續
    宋小朝阅读 165评论 0 0
  • 刚被林心如大婚虐完一个月,这下又被舒淇虐了,这两位黄金剩女终于都婚了!而且,都嫁给了相识多年的老朋友! 这是什么套...
    可闻桃杏香阅读 529评论 0 2
  • 一、理解prototype 我们创建的每一个函数都有一个prototype属性,这个属性是一个指向对象的指针。 构...
    三杯两盏淡茶阅读 3,235评论 0 5
  • 夜幕降临,内心不知是恐惧害怕,还是担心亦或是期待,对于这样的你来说,你觉得是你想要的吗?或许有些事情再怎么强求,也...
    靖兰儿阅读 151评论 0 0