Running external program with redirected stdin and stdout from Java

后端 未结 3 1522
温柔的废话
温柔的废话 2020-11-28 11:21

I\'m trying to running an external program from a Java program and I\'m having trouble. Basically what I\'d like to do would be this:

 Runtime.getRuntime().e         


        
3条回答
  •  感情败类
    2020-11-28 12:26

    If you must use Process, then something like this should work:

    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);
       }
    }
    

    Note:

    • Be sure to close the streams
    • Change this to use buffered streams, I think the raw Input/OutputStreams implementation may copy a byte at a time.
    • The handling of the process will probably change depending on your specific process: cat is the simplest example with piped I/O.

提交回复
热议问题