...
The second compliant solution spawns a command interpreter and executes the user supplied command. It uses a separate OutputStream
to write the output that is read in from the external process.
Code Block | ||
---|---|---|
| ||
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileOutputStream;
class Exec extends Thread {
InputStream is;
String type;
OutputStream os;
Exec(InputStream is, String type) {
this(is, type, null);
}
Exec(InputStream is, String type, OutputStream redirect) {
this.is = is;
this.type = type;
this.os = redirect;
}
public void run() {
try {
PrintWriter pw = null;
if (os != null) {
pw = new PrintWriter(os);
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null) {
if (pw != null) {
pw.println(line);
pw.flush();
}
System.out.println(type + ">" + line);
}
if (pw != null)
pw.flush();
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}
public class ExecMe {
public static void main(String[] args)
{
// ... perform command argument check ...
try {
FileOutputStream fos = new FileOutputStream("c:\\output.txt");
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("notemaker");
// any error message?
Exec errorGobbler = new Exec(proc.getErrorStream(), "ERROR");
// any output?
Exec outputGobbler = new Exec(proc.getInputStream(), "OUTPUT", fos);
errorGobbler.start();
outputGobbler.start();
// any error?
int exitVal = proc.waitFor();
errorGobbler.join(); //handle condition where the
outputGobbler.join(); //process ends before the threads finish
fos.flush();
fos.close();
} catch (Throwable t) { t.printStackTrace(); }
}
}
|
...