我知道如何从我的java应用程序执行shell命令。它应该是这样的:
String command = "java -version";
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
}
catch (IOException e) {
System.out.print(e);
}
我希望将此命令的输出返回到我的java应用程序,而不将输出打印到某个临时文件,然后我从我的应用程序中读取。这可能吗?
答案 0 :(得分:3)
您需要使用ProcessBuilder
Process process = new ProcessBuilder(
"C:\\PathToExe\\exe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:", Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
已经在stackoverflow上找到的代码在java中执行外部程序