1

我想用 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()返回一个Runtimeobject

现在,问题是,当我在命令行中执行“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);
}
4

3 回答 3

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();
于 2012-06-07T12:47:35.787 回答
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
于 2012-06-07T12:44:08.000 回答
0

使用ProcessBuilder 而不是运行时。

喜欢:

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));
于 2012-06-07T12:47:34.673 回答