最近項目中需要在在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); }}
本以為會取巧一下,但是實際結果為,都不會執行了,即整個返回為空白,第一條和第二條都沒有執行。 解決方案
google了一下:http://stackoverflow.com/questions/21908645/command-in-runtime-getruntime-exec-not-working
按照上述的方案將代碼改為
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"});
至此,問題解決。
原理解析:(待補充- -)