Running an external program with redirected stdin and stdout from Java

I am trying to run an external program from a Java program and am having problems. Basically, I would like to do the following:

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

However, I found that this will not work - Java apparently needs to use Process with input and output streams and other things that I do not encounter.

I looked at a number of examples on the Internet (many of which relate to SO), and there seems to be no simple standard way to do this, which for those who do not quite understand what is happening can be quite unpleasant.

I also had problems trying to create my own code with other people's code examples, because, as a rule, most other people 1. are not interested in redirecting stdin , but 2. do not necessarily redirect stdout to a file, and instead System.out .

So, can anyone point me towards any good simple code templates for calling external programs and redirecting stdin and stdout ? Thanks.

+4
source share
3 answers

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:

  • Required close streams
  • Change this to use buffered streams, I think the original implementation of Input/OutputStreams can copy bytes at a time.
  • The processing of the process is likely to change depending on your specific process: cat is the simplest example with channel I / O.
+5
source

You can try something like this:

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

Have you tried System.setIn and System.setOut? exists since JDK 1.0.

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

All Articles