Get output of a running bash script with java
This question already has an answer here:
In your case using .wait(1000), is totally wrong. That's what the exception also tells you.
Exactly for your usecase there's waitFor(long timeout, TimeUnit unit)
:
p.waitFor(10, TimeUnit.SECONDS);
Below is the complete example of the solution. A separate thread switches a flag for the main thread to terminate and then output the collected lines:
private static boolean triggerToClose = false;
public static void main(String[] args) throws IOException,
InterruptedException {
ProcessBuilder pb =
new ProcessBuilder("/home/myscript");
Process p = pb.start();
java.io.InputStream is = p.getInputStream();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(is));
String inputRead;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
triggerToClose = true;
}
}).start();
StringBuilder sb = new StringBuilder();
while ((inputRead = stdInput.readLine()) != null) {
if (triggerToClose) {
p.destroy();
break;
}
sb.append(inputRead).append('n');
}
System.out.println(sb);
}
链接地址: http://www.djcxy.com/p/92140.html
上一篇: 在java中提供关于等待和睡眠的详细信息