使用 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