使用 Java 查找可用磁盘空间


java.io.File 类提供了以下有用的方法来找出可用的磁盘空间。

序号。方法和描述
1public long getFreeSpace()
返回由该抽象路径名命名的分区的未分配字节数。
2public long getTotalSpace()
返回由该抽象路径名命名的分区大小。
3public long getUsableSpace()
返回由该抽象路径名命名的分区上的此虚拟机可用的字节数。

以下示例展示了上述方法的用法。

最终示例

import java.io.File;
import java.text.NumberFormat;

public class Tester {
   public static void main(String[] args) {

      NumberFormat numberFormat = NumberFormat.getInstance();
      numberFormat.setMaximumFractionDigits(2);
      File cDrive = new File("C:\");

      double freeSpace = cDrive.getFreeSpace();
      double usableSpace = cDrive.getUsableSpace();
      double totalSpace = cDrive.getTotalSpace();
      double oneGB = 1024 * 1024 * 1024;

      System.out.println("Free Space: " +
      numberFormat.format(freeSpace/oneGB) + " GB");
      System.out.println("Usable Space: " +
      numberFormat.format(usableSpace/oneGB) + " GB");
      System.out.println("Total Space: " +
      numberFormat.format(totalSpace/oneGB) + " GB");
   }
}

输出

Free Space: 11.66 GB
Usable Space: 11.66 GB
Total Space: 97.56 GB

更新日期:2020 年 6 月 21 日

801 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.