import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import com.sun.management.OperatingSystemMXBean;
public class Test {
public static void main(String[] args) {
System.out.println("磁盘:" + getDisk());
System.out.println("内存:" + getMemery());
}
/**
* TODO 获取文件系统使用率
*
* @return
*/
private static List<String> getDisk() {
// 操作系统
List<String> list = new ArrayList<String>();
for (char c = 'A'; c <= 'Z'; c++) {
String dirName = c + ":/";
File win = new File(dirName);
if (win.exists()) {
double total = win.getTotalSpace() / 1024.0 / 1024.0 / 1024.0;
double free = win.getFreeSpace() / 1024.0 / 1024.0 / 1024.0;
// 保留一位小数
total = Double.valueOf(String.valueOf(total).substring(0, String.valueOf(total).indexOf(".") + 2));
free = Double.valueOf(String.valueOf(free).substring(0, String.valueOf(free).indexOf(".") + 2));
Double compare = (Double) (1 - free * 1.0 / total) * 100;
String str = c + ":盘 总量:" + total + "G 剩余 " + free + "G 已使用 " + compare.intValue() + "%";
list.add(str);
}
}
return list;
}
/**
* TODO 获取内存使用率
*
* @return
*/
private static String getMemery() {
OperatingSystemMXBean osmxb = (com.sun.management.OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 总的物理内存+虚拟内存
// long totalvirtualMemory = osmxb.getTotalSwapSpaceSize();
// 物理内存(内存条)
long physicalMemorySize = osmxb.getTotalPhysicalMemorySize();
System.out.println("物理内存:" + physicalMemorySize / 1024.0 / 1024.0 / 1024.0);
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
System.out.println("总 的 内 存" + Math.round(physicalMemorySize / 1024.0 / 1024.0 / 1024.0));
System.out.println(
"使用的内存" + Math.round((physicalMemorySize - freePhysicalMemorySize) / 1024.0 / 1024.0 / 1024.0));
Double compare = (Double) (1 - freePhysicalMemorySize * 1.0 / physicalMemorySize) * 100;
String str = "内存已使用:" + compare.intValue() + "%";
return str;
}
}
版权声明:本文为a990914093原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。