使用 Java 查找可用磁盘空间
java.io.File 类提供了以下有用的方法来查明可用的可用磁盘空间。
| 序号 | 方法及说明 |
|---|---|
| 1 | public long getFreeSpace() 返回此抽象路径名所命名的分区中未分配字节数。 |
| 2 | public long getTotalSpace() 返回此抽象路径名所命名的分区的空间大小。 |
| 3 | public 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP