Java 中可以通過 Runtime.getRuntime()
來執行外部命令
在實際中可以用來執行shell 命令一般代碼如下
- shell 文件(簡化)
#!/bin/bash
echo "我是shell命令裏輸出的"
- Java方法代碼
private String exec(String cmd) throws IOException, InterruptedException {
String result;
Process process = Runtime.getRuntime().exec(cmd);
InputStream is;
int wait = process.waitFor();
if (wait == 0) {
is = process.getInputStream();
} else {
is = process.getErrorStream();
}
result = IoUtil.read(is, CharsetUtil.CHARSET_UTF_8);
is.close();
process.destroy();
if (StrUtil.isEmpty(result)) {
result = "沒有返回任何執行信息";
}
return result;
}
- 調用方法代碼
String msg = exec("/test.sh");
System.out.println(msg);
這樣就會輸出 我是shell命令裏輸出的
一次我在使用shell 命令殺進程時遇到了一個問題
shell 命令代碼大致如下
#!/bin/bash
echo "正在殺死進程"
Tag="systemTestPID"
kill $(pgrep -f ${Tag}) 2>/dev/null
echo "完成"