如何利用Java獲取程序的資訊(通過tasklist和cmd與Windows進行互動)
阿新 • • 發佈:2019-02-20
/*********************************************************************** * Project: gpsAdapter * Note: Console Application **********************************************************************/ /** * * @author HuangHaifeng 1.0 * @date 2015-12-26 * @copyright CCompass * */ package com.hhf.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; public class ProcessInfoUtil { // 通過獲取當前執行主機的pidName,擷取獲得他的pid public static String getCurrentPid() throws Exception { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pidName = runtime.getName();// 5296@dell-PC String pid = pidName.substring(0, pidName.indexOf("@")); return pid; } // 通過Pid獲取PidName public static String getPidNameByPid(String pid) throws Exception { String pidName = null; InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String[] array = (String[]) null; try { Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV /FI \"PID EQ " + pid + "\""); is = p.getInputStream(); // "javaw.exe","3856","Console","1","72,292 // K"從這個程序中獲取對應的PidName ir = new InputStreamReader(is); br = new BufferedReader(ir); while ((line = br.readLine()) != null) { if (line.indexOf(pid) != -1) { array = line.split(","); line = array[0].replaceAll("\"", ""); line = line.replaceAll(".exe", "");// 考慮pidName字尾為exe或者EXE line = line.replaceAll(".exe".toUpperCase(), ""); pidName = line; } } } catch (IOException localIOException) { throw new Exception("獲取程序名稱出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } return pidName; } // 根據Pid獲取當前程序的CPU public static String getCPUByPID(String pid) throws Exception { if (pid == null) { return null; } InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String[] array = (String[]) null; try { Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV /FI \"PID EQ " + pid + "\""); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); while ((line = br.readLine()) != null) { if (!"".equals(line)) { array = line.split("\",\""); line = array[3].replaceAll("\"", ""); return line; } } } catch (Exception localException) { throw new Exception("獲取程序CPU資訊出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } return null; } // 根據Pid獲取當前程序的memory public static String getMemByPID(String pid) throws Exception { if (pid == null) { return null; } InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String[] array = (String[]) null; try { Process p = Runtime.getRuntime().exec(" TASKLIST /NH /FO CSV /FI \"PID EQ " + pid + "\""); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); while ((line = br.readLine()) != null) { if (!"".equals(line)) { array = line.split("\",\""); line = array[4].replaceAll("\"", ""); return line; } } } catch (IOException localIOException) { throw new Exception("獲取程序記憶體資訊出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } return null; } // 根據Pid將程序幹掉 public static void killProcessByPid(String pid) throws Exception { Runtime.getRuntime().exec("taskkill /F /PID " + pid); } // 根據PidName將程序幹掉 public static void killProcessByPidName(String pidName) throws Exception { Runtime.getRuntime().exec("taskkill /F /IM " + pidName + ".exe"); } // 根據PidName獲取當前的Pid的list集合 public static List<String> getPIDListByPidName(String pidName) throws Exception { List<String> pidList = new ArrayList<>(); InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String[] array = (String[]) null; try { String imageName = pidName + ".exe"; Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV /FI \"IMAGENAME EQ " + imageName + "\""); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); while ((line = br.readLine()) != null) { if (line.indexOf(imageName) != -1) { array = line.split(","); line = array[1].replaceAll("\"", ""); pidList.add(line); } } } catch (IOException localIOException) { throw new Exception("獲取程序ID出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } return pidList; } // 獲取當前系統的所有的PidName public static Set<String> getCurrOsAllPidNameSet() throws Exception { Set<String> pidNameSet = new HashSet<>(); InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String[] array = (String[]) null; try { Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV"); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); while ((line = br.readLine()) != null) { array = line.split(","); line = array[0].replaceAll("\"", ""); line = line.replaceAll(".exe", ""); line = line.replaceAll(".exe".toUpperCase(), ""); if (StringUtils.isNotBlank(line)) { pidNameSet.add(line); } } } catch (IOException localIOException) { throw new Exception("獲取系統所有程序名出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } return pidNameSet; } // 判斷當前pid是否退出,判斷根據pid查詢的記憶體是否為空來決定 public static boolean isExitPid(String pid) throws Exception { return getMemByPID(pid) != null; } // 對啟動路徑和執行引數的拼接 public static String getCommandFormatStr(String proPath) {// 這樣的思路就可以控制倆種引數的輸入 return getCommandFormatStr(proPath, null); } public static String getCommandFormatStr(String proPath, String runArgs) { StringBuffer command = new StringBuffer(); command.append("\""); command.append(proPath); command.append("\""); if (StringUtils.isNotBlank(runArgs)) { command.append(" ").append(runArgs); } return command.toString(); } // 執行完相應的命令列就退出cmd private static String getCommandByCmd(String cmdStr) { StringBuffer command = new StringBuffer(); command.append("cmd /C "); command.append(cmdStr); return command.toString(); } // 獲取當前環境的Java_Home private static String getJavaHome() throws Exception { String javaHome = System.getenv("JAVA_HOME"); javaHome = javaHome == null ? System.getProperty("java.home") : javaHome; return javaHome; } // 退出Java_Home public static boolean existJavaHome() throws Exception {// 對於這個方法在產品階段用於判斷是否具有JAVA_HOME InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; try { Process p = Runtime.getRuntime().exec("cmd /c echo %JAVA_HOME% "); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); if ((line = br.readLine()) != null) { if (line.indexOf("%JAVA_HOME%") != -1) { return false; } return true; } } catch (IOException localIOException) { throw new Exception("獲取JAVA_HOME資訊出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } return false; } // 通過cmd開啟對應的檔案 public static void openDir(String fileDir) throws Exception {// 開啟cmd,執行explorer Runtime.getRuntime().exec("cmd /c start explorer " + fileDir);// explorer.exe是Windows的程式管理器或者檔案資源管理器 } // 根據當前的Pid獲取當前程序的埠 public static Map<String, List<String>> getPortByPID(String pid) throws Exception { if (pid == null) { return null; } InputStream is = null; InputStreamReader ir = null; BufferedReader br = null; String line = null; String TCP_TYPE = "TCP"; String UDP_TYPE = "UDP"; String LISTENING_STATE_TYPE = "LISTENING";// 狀態值 Map<String, List<String>> portMap = new HashMap<>(); List<String> tcpPortList = new ArrayList<>(); List<String> udpPortList = new ArrayList<>(); portMap.put(TCP_TYPE, tcpPortList); portMap.put(UDP_TYPE, udpPortList); String[] array = (String[]) null; try { Process p = Runtime.getRuntime().exec("netstat /ano"); is = p.getInputStream(); ir = new InputStreamReader(is); br = new BufferedReader(ir); do { if (line.indexOf(pid) != -1) { line = line.replaceFirst("\\s+", ""); if (line.indexOf(TCP_TYPE) != -1) { if (line.indexOf(LISTENING_STATE_TYPE) != -1) { array = line.split("\\s+"); String port = array[1].split(":")[1]; tcpPortList.add(port); } } else { array = line.split("\\s+"); String port = array[1].split(":")[1]; udpPortList.add(port); } } if ((line = br.readLine()) == null) { break; } } while (pid != null); } catch (IOException localIOException) { throw new Exception("獲取程序埠資訊出錯!"); } finally { if (br != null) { br.close(); } if (ir != null) { ir.close(); } if (is != null) { is.close(); } } return portMap; } public static void main(String[] args) throws Exception { System.out.println(getCurrentPid()); // System.out.print(getPortByPID("5116")); System.out.println(getMemByPID("5116")); System.out.println(getJavaHome()); System.out.println(existJavaHome()); String property = System.getProperty("java.home"); System.out.println(property);// E:\Programs\jdk\jre Set<String> set = getCurrOsAllPidNameSet(); for (String string : set) { System.out.println(string); } } }