如何使用Java获取当前打开的窗口/进程的列表?
有没有人知道如何使用Java获取当前打开的窗口或本地计算机的进程?
我试图做的是:列出当前打开的任务,窗口或进程打开,就像在Windows Taskmanager中一样,但使用多平台方法 - 如果可能的话,只使用Java。
有没有人知道如何使用Java获取当前打开的窗口或本地计算机的进程?
我试图做的是:列出当前打开的任务,窗口或进程打开,就像在Windows Taskmanager中一样,但使用多平台方法 - 如果可能的话,只使用Java。
这是从命令“ps -e”解析进程列表的另一种方法:
try {
String line;
Process p = Runtime.getRuntime().exec("ps -e");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
如果您使用的是Windows,那么您应该更改该行:“Process p = Runtime.getRun...”等。。。(第 3 行),对于如下所示的行:
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
希望这些信息有所帮助!
最后,使用Java 9 +可以使用ProcessHandle
:
public static void main(String[] args) {
ProcessHandle.allProcesses()
.forEach(process -> System.out.println(processDetails(process)));
}
private static String processDetails(ProcessHandle process) {
return String.format("%8d %8s %10s %26s %-40s",
process.pid(),
text(process.parent().map(ProcessHandle::pid)),
text(process.info().user()),
text(process.info().startInstant()),
text(process.info().commandLine()));
}
private static String text(Optional<?> optional) {
return optional.map(Object::toString).orElse("-");
}
输出:
1 - root 2017-11-19T18:01:13.100Z /sbin/init
...
639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
...
23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo