java中執行多條shell命令,除了第一條其他都未執行
阿新 • • 發佈:2019-01-04
最近專案中需要在在java中執行shell命令,用了最常見方式,程式碼如下:
public class ShellUtil {
public static String runShell(String shStr) throws Exception {
Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr});
process.waitFor();
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
String result = "";
while ((line = read.readLine())!=null){
result+=line;
}
return result;
}
}
在呼叫時如下呼叫:
public class ExecuteShell {
public static void main (String[] args){
String command = "some command" ;
String message = ShellUtil.runShell(command);
System.out.println(message);
}
}
如果你要同時執行兩個命令或者多個命令的情況下,那麼呼叫就會如下所示:
public class ExecuteShell {
public static void main (String[] args){
String command1 = "some command";
String command2 = "some command";
String message1 = ShellUtil.runShell(command1);
String message2 = ShellUtil.runShell(command2);
System.out .println(message1);
System.out.println(message2);
}
}
當時為了節約效能,改為如下形式:
public class ExecuteShell {
public static void main (String[] args){
String command1 = "some command";
String command2 = "some command";
String command = command1 + " && " + command2;
String message = ShellUtil.runShell(command);
System.out.println(message);
}
}
本以為會取巧一下,但是實際結果為,都不會執行了,即整個返回為空,第一條和第二條都沒有執行。
解決方案
按照上述的方案將程式碼改為
public class ShellUtil {
private static Logger logger = LoggerFactory.getLogger(ShellUtil.class);
public static String runShell(String shStr) throws Exception {
Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr});
process.waitFor();
BufferedReader read = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
String result = "";
while ((line = read.readLine())!=null){
result+=line;
}
return result;
}
}
即將Runtime.getRuntime().exec("command");
改為 Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","command"});
注意:如果是windows作業系統要改為Runtime.getRuntime().exec(new String[]{"**cmd** exe","-c","command"});
至此,問題解決。
原理解析:(待補充- -)