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
You could 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();
have you tried System.setIn and System.setOut? has been around 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" ) );
...
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:
close
the streamsInput/OutputStreams
implementation may copy a byte at a time.cat
is the simplest example with piped I/O.