Java 執行shell 指令碼
阿新 • • 發佈:2019-02-16
直接執行在環境變數path的命令 可能會報錯
Java 會找/bin下面的命令執行
命令路徑要寫絕對的....!!!! 比如/bin/sh 代替 sh
執行命令方法
public static String exec(String cmd) {
System.out.println(cmd);StringBuffer msg = null;
try {
//Process procS = Runtime.getRuntime().exec("source /etc/profile");
//procS.waitFor(); // 阻塞,直到上述命令執行完
Process proc = Runtime.getRuntime().exec(cmd);
int code = proc.waitFor(); // 阻塞,直到上述命令執行完
System.out.println(code);
msg = new StringBuffer();
String line;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((line = bufferedReader.readLine()) != null){
msg.append(line);
}
bufferedReader.close();
System.out.println(msg.toString());
//int code = proc.waitFor();
return msg.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}