执行linux命令
简单版本
Process process = Runtime.getRuntime().exec("sh /Users/bindo/test.sh" );
InputStreamReader ips = new InputStreamReader(process.getInputStream());
BufferedReader br = new BufferedReader(ips);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
注:执行其它命令,直接输入命令即可,如果是.sh文件,则必须遵循格式: sh +shell脚本文件
封装版本
public static void executeOneMore(List<String> commands) {
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
out.println("exit");// 结束命令
String rspLine = "";
while ((rspLine = in.readLine()) != null) {
System.out.println(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
List<String> commands= new ArrayList<>();
commands.add("pwd");
commands.add("cd ~");
// 执行shell脚本,必备sh命令
commands.add("sh ./test.sh");
executeOneMore(commands);
}