使用 com.sun.management.OperatingSystemMXBean(繼承自標準 java.lang.management.OperatingSystemMXBean),需強制轉型。
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class OSTest {
public static void main(String[] args) {
OperatingSystemMXBean osmb = (OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
long totalMB = osmb.getTotalPhysicalMemorySize() / 1024 / 1024;
long freeMB = osmb.getFreePhysicalMemorySize() / 1024 / 1024;
System.out.println("系統物理記憶體總計:" + totalMB + " MB");
System.out.println("系統可用記憶體總計:" + freeMB + " MB");
}
}
注意:ManagementFactory.getOperatingSystemMXBean() 回傳標準介面,必須轉型為 com.sun.management.OperatingSystemMXBean 才能取得 getTotalPhysicalMemorySize() 等方法。
File.listRoots() 取得所有根分區,getTotalSpace()、getFreeSpace()、getUsableSpace() 分別回傳總容量、剩餘空間、可用空間(考慮寫入權限)。
import java.io.File;
public class DiskFree {
public static void main(String[] args) {
File[] roots = File.listRoots();
for (File root : roots) {
System.out.println(root.getPath() + " 資訊如下:");
System.out.println("總容量 = " + root.getTotalSpace() / 1024 / 1024 / 1024 + " GB");
System.out.println("剩餘空間 = " + root.getFreeSpace() / 1024 / 1024 / 1024 + " GB");
System.out.println("可用空間 = " + root.getUsableSpace() / 1024 / 1024 / 1024 + " GB");
System.out.println();
}
}
}
public class SystemSnapshot {
public static void main(String[] args) {
// 記憶體
OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
System.out.printf("Memory: Total=%,d MB, Free=%,d MB%n",
osmb.getTotalPhysicalMemorySize()/1024/1024,
osmb.getFreePhysicalMemorySize()/1024/1024);
// 磁碟
for (File root : File.listRoots()) {
System.out.printf("Disk %s: Total=%,d GB, Free=%,d GB, Usable=%,d GB%n",
root.getPath(),
root.getTotalSpace()/1024/1024/1024,
root.getFreeSpace()/1024/1024/1024,
root.getUsableSpace()/1024/1024/1024);
}
}
}