与重定向标准输入运行外部程序,并从Java标准输出与重定向标准输入运行外部程序,并从Java标准输出

2019-06-14 14:44发布

我试图从Java程序中运行外部程序,我有麻烦了。 基本上我想要做什么会是这样的:

 Runtime.getRuntime().exec("./extprogram <fileIn >fileOut");

但是我发现还是不行- Java的apparentls需要使用Process的输入和输出流,并且我不跟经验丰富的其他东西。

我已经看了一些在互联网上的例子(其中许多是从SO),并且似乎没有被这样做的一个简单的标准方式,也有人谁不完全明白是怎么回事,可以说是相当令人沮丧。

我也有麻烦试图建立自己的代码断别人的代码示例,因为通常它似乎其他大多数人1.不感兴趣的重定向stdin和2不一定重定向stdout到一个文件,但而不是System.out

所以,会有人能够指出我的任何好的简单的代码模板的方向调用外部程序,重定向stdinstdout ? 谢谢。

Answer 1:

如果你必须使用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的最简单的例子。


Answer 2:

你可以尝试这样的事:

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


Answer 3:

你尝试过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" ) );
    ...


文章来源: Running external program with redirected stdin and stdout from Java