我必须在我的java程序中运行jps -l命令并获取输出。我已经尝试了下面提到的代码,但它不起作用。
Runtime rt = Runtime.getRuntime();
proc = rt.exec("jps -l");
Runtime rt = Runtime.getRuntime();
proc = rt.exec("cmd.exe /c start jps -l");
Runtime rt = Runtime.getRuntime();
proc = rt.exec("powershell.exe jps -l");
每次程序输出为:
Cannot run program "jps -l": CreateProcess error=2, The system cannot find the file specified
有没有办法运行"jps -l“并获取输出?
发布于 2021-10-26 04:39:52
jps很可能不在系统路径上。您仍然可以运行该可执行文件,只需提供绝对路径,例如
"c:\Program Files\Java\openjdk-17.0.2\bin\jps.exe" -l
注意,“Program Files”包含一个需要转义的空格。
发布于 2021-10-26 04:42:47
您需要为Java设置环境变量,有关如何设置,请参考how to set java path。
证明:
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("jps -l");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.out.println("Done");
}
}
输出:
Here is the standard output of the command:
17556 jdk.jcmd/sun.tools.jps.Jps
13320 com.example.demo.Test
22636 Eclipse
Here is the standard error of the command (if any):
Done
环境变量:
https://stackoverflow.com/questions/69721968
复制