使用重定向的stdin和stdout从Java运行外部程序

我正在尝试从Java程序运行外部程序,我遇到了麻烦。 基本上我想做的就是:

Runtime.getRuntime().exec("./extprogram fileOut"); 

但是我发现这不起作用–Java表达式需要使用带有输入和输出流的Process以及其他我没有遇到过的东西。

我已经看过互联网上的一些例子(其中很多来自SO),并且似乎没有一种简单的标准方法可以做到这一点,对于那些不完全了解正在发生的事情的人来说,可能会非常令人沮丧。

我也难以尝试从其他人的代码示例中构建我自己的代码,因为通常看起来大多数其他人1.对重定向stdin不感兴趣,并且2.不一定将stdout重定向到文件,但是而不是System.out

那么,是否有人能够指出任何好的简单代码模板的方向来调用外部程序并重定向stdinstdout ? 谢谢。

如果你必须使用Process ,那么这样的东西应该有效:

 public static void pipeStream(InputStream input, OutputStream output) throws IOException { byte buffer[] = new byte[1024]; int numRead = 0; do { numRead = input.read(buffer); output.write(buffer, 0, numRead); } while (input.available() > 0); output.flush(); } public static void main(String[] argv) { FileInputStream fileIn = null; FileOutputStream fileOut = null; OutputStream procIn = null; InputStream procOut = null; try { fileIn = new FileInputStream("test.txt"); fileOut = new FileOutputStream("testOut.txt"); Process process = Runtime.getRuntime().exec ("/bin/cat"); procIn = process.getOutputStream(); procOut = process.getInputStream(); pipeStream(fileIn, procIn); pipeStream(procOut, fileOut); } catch (IOException ioe) { System.out.println(ioe); } } 

注意:

  • 一定要close溪流
  • 改为使用缓冲流,我认为原始的Input/OutputStreams实现可以一次复制一个字节。
  • 处理过程可能会根据您的具体过程而改变: cat是管道I / O最简单的示例。

你可以尝试这样的事情:

 ProcessBuilder pb = new ProcessBuilder(); pb.redirectInput(new FileInputStream(new File(infile)); pb.redirectOutput(new FileOutputStream(new File(outfile)); pb.command(cmd); pb.start().waitFor(); 

你试过System.setIn和System.setOut吗? 自JDK 1.0以来一直存在。

 public class MyClass { System.setIn( new FileInputStream( "fileIn.txt" ) ); int oneByte = (char) System.in.read(); ... System.setOut( new FileOutputStream( "fileOut.txt" ) ); ...