我想用Java执行操作系统命令,然后打印出它的返回值。像这样:
这就是我想要的......
String location_of_my_exe_and_some_parameters = "c:\\blabla.exe /hello -hi";
Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
我尝试将System.out.print()放在Runtime ...行的开头,但是失败了。因为,显然是getRuntime()
returns a Runtime
object。
现在,问题是,当我在命令行中执行“blabla.exe / hello -hi”命令时,我得到了一个结果:“你执行了一些命令,欢呼!”。但是,在Java中,我什么都没得到。
我尝试将返回值放入Runtime
对象和Object
对象。但是,他们都失败了。我怎么能做到这一点?
解决了问题 - 这是我的解决方案
Process process = new ProcessBuilder(location, args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
答案 0 :(得分:1)
请注意Runtime.exec(...)
会返回Process
个对象。您可以使用此对象捕获其输入流并检索它打印到标准输出的任何内容:
Process p = Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
InputStream is = p.getInputStream();
// read process output from is
答案 1 :(得分:1)
您可以使用以下方法捕获命令的输出:
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
log.info(line);
}
//This will wait for the return code of the process
int exitVal = pr.waitFor();
答案 2 :(得分:0)
UseProcessBuilder而不是Runtime。
喜欢:
Process process = new ProcessBuilder("c:\\blabla.exe","param1","param2").start();
<强>答案:强>
Process process = new ProcessBuilder("c:\\blabla.exe","/hello","-hi").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));