如何在Java中獲取當前開啟程序的列表?
瞭解系統中執行的程序(無論是前臺程序還是後臺程序)對於使用者至關重要。在 Windows 中,我們有任務管理器,但它內部使用一個名為 tasklist 的程式。除了提供當前執行的程序外,tasklist 還提供每個程序的詳細資訊,例如程序 ID、會話名稱、會話和記憶體使用情況。
在本文中,我們將瞭解如何使用 Java 程式語言獲取當前開啟程序的列表。
演算法
步驟 1 - 建立一個執行 tasklist.exe 的程序。
步驟 2 - 建立一個 BufferedReader 類,它接收程序物件。
步驟 3 - 使用 while 迴圈逐行讀取程序詳細資訊並打印出來。
語法
要執行位於 system32 資料夾中的 tasklist.exe,我們需要呼叫一個程序物件,然後執行。
以下是使用該方法執行 tasklist.exe 程式的語法
Process process_object = Runtime.getRuntime().exec(System.getenv("windir") + "\system32" + "tasklist.exe");
注意此程式無法在任何線上編輯器中執行。要在本地系統中獲取當前開啟程序的列表,您需要僅在本地編輯器(Java IDE)中執行它。
方法:使用 tasklist.exe 列出所有活動程序
在這種方法中,我們呼叫一個在 WIN32 資料夾中執行 tasklist.exe 的程序。之後,我們使用 BufferedReader 讀取所有活動程序,並逐個將其列印到控制檯。
示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
// String variable to store process details
String processes;
// Execute tasklis.exe from win32
Process p = Runtime.getRuntime().exec(System.getenv("windir") + "\system32" + "tasklist.exe");
// Buffered reader to read from the process object
BufferedReader br = new BufferedReader(newInputStreamReader(p.getInputStream()));
// Prints all processes one by one
while ((processes = br.readLine()) != null) {
System.out.println(processes);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
輸出
Image Name PID Session Name Session# Mem Usage ========================= ======== ================ =========== ============ System Idle Process 0 Services 0 8 K System 4 Services 0 9,416 K Registry 140 Services 0 30,420 K smss.exe 604 Services 0 1,076 K csrss.exe 976 Services 0 5,936 K csrss.exe 1112 Console 1 14,144 K winlogon.exe 1164 Console 1 11,704 K wininit.exe 1216 Services 0 6,628 K services.exe 1260 Services 0 9,804 K lsass.exe 1276 Services 0 27,360 K svchost.exe 1396 Services 0 1,388 K fontdrvhost.exe 1428 Console 1 6,608 K ...
在本文中,我們探討了如何在 Java 中查詢當前開啟程序的列表。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP