I/O with external command
Hi,
I'm trying to run an external command inside my Java program and then
manage the I/O with that program with the console.
I paste the code
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
public class RunExternalCommand {
public static int runCommand(String command) {
Process proc = null;
try {
proc = Runtime.getRuntime().exec(command);
StreamGobbler outThread = new
StreamGobbler(proc.getInputStream(),
"OUT");
StreamGobbler errThread = new
StreamGobbler(proc.getErrorStream(),
"ERR");
StreamGobbler stdinThread = new StreamGobbler(System.in, proc
.getOutputStream(), "STDIN");
stdinThread.start();
outThread.start();
errThread.start();
proc.waitFor();
} catch (IOException e) {
} catch (InterruptedException e) {
}
return 0;
}
}
class StreamGobbler extends Thread {
InputStream is;
PrintStream out;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.out = System.out;
this.type = type;
}
StreamGobbler(InputStream is, OutputStream os, String type) {
this.is = is;
this.out = new PrintStream(os);
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
int b = 0;
while ((b = isr.read()) != -1) {
out.print((char) b);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
I can run the external command (I see the output). However, when I have
to insert some input and then press Enter, the external command doesn't
get what I write and it's stuck waiting for input.
Any ideas?
Thanks