import java.io.*; class Sysexecute { public static void main(String args[]) throws IOException,InterruptedException,IllegalThreadStateException { Runtime rt= Runtime.getRuntime(); Process p=rt.exec("ls"); System.out.println(p.exitValue()); } }
我正在学习如何在java中执行系统命令,并发生此错误.我尝试使用抛出来否定它但没有用.请解释原因和解决方案
actual error:- Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited at java.lang.UNIXProcess.exitValue(UNIXProcess.java:270) at Sysexecute.main(Sysexecute.java:8)
解决方法
在尝试获取退出值之前调用
Process#waitFor()
.这将阻止当前线程,直到生成的进程终止.如果你不这样做,Process#exitValue()
会抛出
IllegalThreadStateException – if the subprocess represented by this
Process
object has not yet terminated