代码
package test02.getMemory; import oshi.SystemInfo; import oshi.hardware.GlobalMemory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; /** * @Author yxchun * @date 2022/8/6 15:17 * @Des 获取具体进程的占用内存大小 **/ public class MemoryList { private static List<String> specifiedCaption=new ArrayList<String>(); public static void exec(){ specifiedCaption.add("idea64.exe"); specifiedCaption.add("java.exe"); specifiedCaption.add("mysqld.exe"); String execStr=""; for(String name:specifiedCaption){ execStr = "tasklist | findstr /i "+name; String [] cmd={"cmd","/C",execStr}; try { Process process =Runtime.getRuntime().exec(cmd); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"utf-8")); String str=""; // System.out.println(reader.readLine()); while((str=reader.readLine())!=null){ if("".equals(str)){ System.out.println("kong"); continue; } // System.out.println(str); System.out.println(name+" : "+getMemory(str)); }
reader.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { exec(); } public static String getMemory(String str){ // System.out.println(str); String[] s = str.split(" "); String result=null; for(String ss:s){ if(ss.contains("K")){ result=ss; } } result = result.replace(",",""); // System.out.println(result); double i=Double.parseDouble(result.substring(0, (result.length()-2))); double i2=getAllMemory(); double rr = i/(i2/1024); //8360611840 DecimalFormat df = new DecimalFormat("0.00%"); return df.format(rr); } public static double getAllMemory(){ SystemInfo systemInfo = new SystemInfo(); GlobalMemory memory = systemInfo.getHardware().getMemory(); return memory.getTotal(); } }
需要jar包
<dependency> <groupId>com.github.oshi</groupId> <artifactId>oshi-core</artifactId> <version>3.5.0</version> </dependency>
解析:
执行命令
String [] cmd={"cmd","/C","tasklist | findstr /i idea64.exe"};
尝试在命令行运行
读取命令行运行结果
Process process =Runtime.getRuntime().exec(cmd); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"utf-8"));
获取当前计算机内存大小
SystemInfo systemInfo = new SystemInfo(); GlobalMemory memory = systemInfo.getHardware().getMemory(); return memory.getTotal();