Windows 下執行 dir 並解析最後一行可用空間。範例程式 Diskspace.java:
public class Diskspace {
public static long getFreeDiskSpace(String dirName) {
String os = System.getProperty("os.name");
String cmd = (os.equals("Windows NT") || os.equals("Windows 2000"))
? "cmd.exe /c dir " + dirName
: "command.com /c dir " + dirName;
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line, last = null;
while ((line = in.readLine()) != null) last = line;
p.destroy();
if (last == null) return -1;
last = last.trim().replaceAll("[.,]", "");
String[] items = last.split(" ");
for (int i = 1; i < items.length; i++) {
try { return Long.parseLong(items[i]); } catch (NumberFormatException ignored) {}
}
return -1;
}
public static void main(String[] args) {
if (args.length == 0) {
for (char c = 'A'; c <= 'Z'; c++) System.out.println(c + ":\\ " + getFreeDiskSpace(c + ":\\"));
} else for (String d : args) System.out.println(d + " " + getFreeDiskSpace(d));
}
}
缺點:Linux/Unix 需另寫 df -k 解析邏輯,維護成本高。
FileRegistry.getVolumes() 取得 DiskVolume 陣列。getFreeSpace() 與 getMaxCapacity() 即得可用/總容量。優點:純 Java、跨平台、API 簡潔。
GetDiskFreeSpaceEx、Linux statvfs)。System.loadLibrary 載入,native 方法映射。| 場景 | 推薦方案 |
|---|---|
| 僅 Windows、快速原型 | 方案一 (命令列解析) |
| 跨平台生產環境、標準需求 | 方案二 (JConfig) |
| 特殊檔案系統、極致效能、既有 C 庫 | 方案三 (JNI) |
JDK 6+ 已內建 File.getFreeSpace()/getTotalSpace()/getUsableSpace(),現代專案優先使用標準 API,無需第三方庫。