您应该始终在单独的线程(使用 StreamGobbler)中捕获进程的错误流,以处理进程抛出错误的情况。
class StreamGobbler extends Thread
{
private InputStream is;
private String myMessage;
public StreamGobbler(InputStream istream)
{
this.is = istream;
}
public String getMessage()
{
return this.myMessage;
}
@Override
public void run()
{
StringBuilder buffer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
int size = 1024 * 1024;
char[] ch = new char[size];
int read = 0;
try {
while ((read = br.read(ch, 0, size)) >= 0) {
buffer.append(ch, 0, read);
}
}
catch (Exception ioe) {
ioe.printStackTrace();
}
finally {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
this.myMessage = buffer.toString();
return;
}
}
然后你应该使用 StreamGobbler 来捕获错误流,如下所示:
Process process =
new ProcessBuilder("find", Main.serversPath, "-name", "'dynmap'").start();
StreamGobbler error = new StreamGobbler(process.getErrorStream());
error.start();
BufferedReader stdInput =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((s = stdInput.readLine()) != null) {
filesToDelete.add(s);
if (Main.debugMode.equals("High")) {
System.out.println("Preprocess: dynmap pass - found " + s);
}
}
// Get the exit status
int exitStatus = process.waitFor();
if (exitStatus != 0) {
// read the error.getMessage() and handle accordingly.
}
process.destroy();
另外,推荐使用ProcessBuilder来创建流程。