java中执⾏多条shell命令,除了第⼀条其他都未执⾏最近项⽬中需要在在java中执⾏shell命令,⽤了最常见⽅式,代码如下:
public class ShellUtil {
public static String runShell(String shStr) throws Exception {
Process process;
process = Runtime().exec(new String[]{"/bin/sh","-c",shStr});
process.waitFor();
BufferedReader read = new BufferedReader(new InputStream()));
String line = null;
String result = "";
while ((line = adLine())!=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 = Logger(ShellUtil.class);
public static String runShell(String shStr) throws Exception {
Process process;
process = Runtime().exec(new String[]{"/bin/sh","-c",shStr});
process.waitFor();
BufferedReader read = new BufferedReader(new InputStream()));
String line = null;
String result = "";
while ((line = adLine())!=null){
result+=line;
}
return result;
}
}
即将Runtime().exec("command"); 改为 Runtime().exec(new String[]{"/bin/sh","-c","command"});注意:如果是windows操作系统要改为Runtime().exec(new String[]{"**cmd** exe","-c","command"});shell代码
⾄此,问题解决。
原理解析:(待补充- -)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论