java 利用 ProcessBuilder 执行本地命令或者脚本
package ExecLocalCommand;
import ;
import ;
public class ProcessBuilderDemo {
public void exeLocalCommand(String exportCmd) throws Exception{
ProcessBuilder builder;
String charSet;
String os = ("");
if (().contains("win")) {
builder = new ProcessBuilder("cmd", "/c", ());
charSet = "gbk";
} else {
builder = new ProcessBuilder("sh", "-c", ());
charSet = "utf-8";
}
//重定向错误日志信息到 inputstream,很重要,不然错误信息无法抓取到
(true);
Process process = ();
BufferedReader br = new BufferedReader(new InputStreamReader((),charSet));
String line = null;
while ((line = ()) != null) {
line = ();
(line);
}
// 等待命令执行完成
int code = ();
if (code == 0) {
//通常情况0 表示命令或者脚本正常退出,但是如果脚本自己有返回状态这里需要根据自己状态判断
("success");
} else {
("fail");
}
}
}