我有一个问题,我尝试从 java 代码运行一个 sh 文件来启动一个 JBoss 服务器,所以当我执行这个 sh 文件时,我想知道它什么时候启动并打印出我的控制台。这是我的代码:
public static void runStart() {
try {
String command = "./Run.sh";
String s = get_commandline_results(command);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("done");
}
public static String get_commandline_results(String cmd)
throws IOException, InterruptedException, IllegalCommandException {
String result = "";
Process p = null;
p = Runtime.getRuntime().exec(String.format("bash -c %s", cmd));
final ProcessResultReader stderr = new ProcessResultReader(
p.getErrorStream(), "STDERR");
final ProcessResultReader stdout = new ProcessResultReader(
p.getInputStream(), "STDOUT");
System.out.println("starting...");
stderr.start();
stdout.start();
final int exitValue = p.waitFor();// It was delayed here because sh not complete
System.out.println("started!");// How to go to here?
if (exitValue == 0) {
result = stdout.toString();
} else {
result = stderr.toString();
}
return result;
}
}
class ProcessResultReader extends Thread {
final InputStream is;
final String type;
final StringBuilder sb;
ProcessResultReader(final InputStream is, String type) {
this.is = is;
this.type = type;
this.sb = new StringBuilder();
}
public void run() {
try {
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
this.sb.append(line).append("\n");
}
} catch (final IOException ioe) {
System.err.println(ioe.getMessage());
throw new RuntimeException(ioe);
}
}
@Override
public String toString() {
return this.sb.toString();
}
}
感谢您的帮助!