Java Runtime.exec problem
HI,
I am using Runtime.exec to excute my unix (wrapper) commands.
These commands are fired consecutively.
But somtimes i get following exception,
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:
145)
at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
at sun.nio.cs.StreamDecoder$CharsetSD.readBytes(StreamDecoder.java:
411)
at sun.nio.cs.StreamDecoder$CharsetSD.implRead(StreamDecoder.java:
453)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:183)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at com.vistaar.web.util.StreamGobbler.run(ToolkitAgent.java:711)
Following is the code snippet:
//method from which exec is invoked
public static String processCommandWithNewLine(String
commandToExecute) {
Runtime systemShell = Runtime.getRuntime();
Process outputProcess = null;
String toolkitOutput = "";
try {
LogHelper.debug(lg, commandToExecute);
outputProcess = systemShell.exec(commandToExecute);
StreamGobbler errorGobbler = new StreamGobbler
(outputProcess.getErrorStream(), true, lg);
StreamGobbler outputGobbler = new StreamGobbler
(outputProcess.getInputStream(), true, lg);
errorGobbler.start();
outputGobbler.start();
outputProcess.waitFor();
toolkitOutput = toolkitOutput + outputGobbler.getOutput();
toolkitOutput = toolkitOutput + errorGobbler.getOutput();
LogHelper.debug(lg, toolkitOutput);
} catch (Throwable ex) {
LogHelper.printErrorTrace(lg, ex);
} finally {
closeProcessStreams(outputProcess);
}
return toolkitOutput.trim();
}
// steam gobbler implmentaion to read output of the command
class StreamGobbler extends Thread {
InputStream is;
String output = "";
boolean insertNewLine;
Logger lg;
StreamGobbler(InputStream is, boolean insertNewLine, Logger lg) {
this.is = is;
this.insertNewLine = insertNewLine;
this.lg = lg;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
if (insertNewLine) {
while ((line = br.readLine()) != null) {
output = output + line + "\n";
}
} else {
while ((line = br.readLine()) != null) {
output = output + line;
}
}
} catch (IOException ioe) {
LogHelper.printErrorTrace(lg, ioe);
}
}
public String getOutput() {
return output;
}
}
1. i m using thread to read output & error stream simultaneously
2. the above problem doesn't come consistently, but comes frequently
eventhough the program says "stream closed",
when i fire same command from shell it gives me proper output
any idea what is causing the problem?
or der there any better way to read output given by exec process?
thnx,
suraj