cmd一些命令
1、查看内存占用情况
wmic OS get FreePhysicalMemory
2、查看系统内存总数
wmic ComputerSystem get TotalPhysicalMemory
3、查看CPU占用情况
wmic cpu get loadpercentage
4、查看每个磁盘使用情况
wmic logicaldisk get Caption,Description,FreeSpace,Size
这里不借用外部依赖包,直接用cmd获取磁盘,OperatingSystemMXBean对象获取内存(import com.sun.management.OperatingSystemMXBean;);
cpu不准就不写了,谁会教我一下!
try {
Process process = Runtime.getRuntime().exec("wmic logicaldisk get Caption,Description,FreeSpace,Size");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (!line.trim().isEmpty() && !line.startsWith("Caption") && !line.startsWith("Description")) {
String[] parts = line.split("\\s+");
if (parts.length >= 4) {
long freeSpace = Long.parseLong(parts[2]);
long totalSize = Long.parseLong(parts[3]);
String sn = String.format("%.2f", (double) freeSpace / (1024 * 1024 * 1024));
long zn = totalSize / (1024 * 1024 * 1024); // 总不需要精取
double usagePercentage = ((totalSize - freeSpace) / (double) totalSize) * 100;
System.out.printf("磁盘 %s 总 %s GB, 剩余 %s GB, 使用率: %.2f%%", parts[0], zn, sn, usagePercentage);
System.out.println();
}
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
// 内存
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
long totalPhysicalMemorySize = osBean.getTotalPhysicalMemorySize();
long freePhysicalMemorySize = osBean.getFreePhysicalMemorySize();
String zn = String.format("%.1f", (double) totalPhysicalMemorySize / (1024 * 1024 * 1024));
String sn = String.format("%.1f", (double) freePhysicalMemorySize / (1024 * 1024 * 1024));
String usagePercentage = String.format("%.2f%%", ((totalPhysicalMemorySize - freePhysicalMemorySize) / (double) totalPhysicalMemorySize) * 100);
System.out.println("总物理内存: " + zn + " GB,可用物理内存: " + sn + " GB,使用率: " + usagePercentage);
还有个简单方法:获取当前项目所在的盘总量和剩余量
try {
File file = new File("/");
long totalSize = file.getTotalSpace();
long freeSpace = file.getFreeSpace();
long zn = totalSize / (1024 * 1024 * 1024);
String yn = String.format("%.2f", (double) (totalSize - freeSpace) / (1024 * 1024 * 1024));
backup.setDiskLength(String.valueOf(zn));
backup.setDiskUesLength(yn);
log.info(String.format("总 %s GB, 剩余 %s GB", zn, yn));
} catch (Exception e) {
e.printStackTrace();
}