使用Runtime.getRuntime().exec执行Shell
执行命令时出现问题, 应用程序会挂起 并没有执行,也没有结果
StringBuffer result = new StringBuffer();
try {
Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", execute});
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
if (returnOne) {
if ((line = in.readLine()) != null) {
result.append(line);
}
} else {
while((line = in.readLine()) != null) {
result.append(line);
}
}
System.out.println("执行Shell脚本 结束", line);
in.close();
int exitValue = proc.waitFor();
if (0 != exitValue) {
log.error("执行Shell脚本失败. error code is :" + exitValue);
}
} catch (IOException var8) {
var8.printStackTrace();
log.error("执行Shell脚本失败 {}", execute, var8);
} catch (InterruptedException var9) {
var9.printStackTrace();
log.error("执行Shell脚本失败~ {}", execute, var9);
}
查了资料才指定Runtime.getRuntime().exec 同时产生InputStream,ErrorStream,2个流是并行。 当前从输出流传输的数据填满了操作系统缓冲区,您的exec命令将自动暂停,以便读者有机会清空缓冲区.但该程序仍将等待输出处理.因此,发生了挂起.所以需要使用线程读取
需要创建一个单独的类来处理输入和错误流,如下所示,
public class ReadStream implements Runnable {
String name;
InputStream is;
Thread thread;
public ReadStream(String name, InputStream is) {
this.name = name;
this.is = is;
}
public void start () {
thread = new Thread (this);
thread.start ();
}
public void run () {
try {
InputStreamReader isr = new InputStreamReader (is);
BufferedReader br = new BufferedReader (isr);
while (true) {
String s = br.readLine ();
if (s == null) break;
System.out.println ("[" + name + "] " + s);
}
is.close ();
} catch (Exception ex) {
System.out.println ("Problem reading stream " + name + "... :" + ex);
ex.printStackTrace ();
}
}
}
最终代码改成
StringBuffer result = new StringBuffer();
try {
Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", execute});
ReadStream s2 = new ReadStream("执行Shell脚本错误", proc.getErrorStream());
s2.start();
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
if (returnOne) {
if ((line = in.readLine()) != null) {
result.append(line);
}
} else {
while((line = in.readLine()) != null) {
result.append(line);
}
}
System.out.println("执行Shell脚本 结束", line);
in.close();
int exitValue = proc.waitFor();
if (0 != exitValue) {
log.error("执行Shell脚本失败. error code is :" + exitValue);
}
} catch (IOException var8) {
var8.printStackTrace();
log.error("执行Shell脚本失败 {}", execute, var8);
} catch (InterruptedException var9) {
var9.printStackTrace();
log.error("执行Shell脚本失败~ {}", execute, var9);
}