public class ShellUtils {
public static void main(String[] args) {
String str = ShellUtils.execute("cd");
//String str = ShellUtils.execute("/myfolder/firstShell.sh 10");
System.out.println(str);
}
public static String execute(String command){
Scanner input = null;
String result = "";
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
//等待命令执行完成
process.waitFor();
InputStream in = process.getInputStream();
input = new Scanner(in);
while(input.hasNext()){
result += input.nextLine() +"\n";
}
result = command + "\n" + result;
} catch (Exception e) {
e.printStackTrace();
}finally {
if(input != null){
input.close();
}
if(process != null){
process.destroy();
}
}
return result;
}
}
异常/错误:
1.Cannot run program "cd": CreateProcess error=2,
原因:执行Linux命令和Windows命令有区别
执行Windows:.exec(cmd /c comand);
执行Linux命令:.exec(command);