How can I write a program which will run another java program (should invoke that program) give the input to that program from this program and get the output and print the output to a file.
+8
A:
Use ProcessBuilder
Example:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Process p = pb.start();
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream();
// Write to input of the program using outputstream here
...
// Read output of program from input stream here
// ...
FileOutputStream fileOut = new FileOutputStream("output.txt");
BufferedInputStream bIn = new BufferedInputStream(in);
byte buf = new byte[4096];
int count;
while ((count = bIn.read(buf)) != -1) {
fileOut.write(buf, 0, count);
}
...
fileOut.close();
bIn.close();
// Exception handling is left as an exercise for the reader :-P
Mark Renouf
2009-02-02 13:27:05
I hadn't heard of the ProcessBuilder class before. Thanks for the tip!
Adam Paynter
2009-02-02 13:51:12