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暑期编程PK赛 得CSDN机械键盘等精美礼品!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 commands= new ArrayList<>(); commands.add("pwd"); commands.add("cd ~"); // 执行shell脚本,必备sh命令 commands.add("sh ./test.sh"); executeOneMore(commands); }



