最近项目需要用java调用shell,在网找找了些文章,总结如下:
import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; public class Shell { public static void main(String[] args) { try { runShell("/root/shell/test.sh arg1 arg2 arg3"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 调用shell, * parameter:arg1 arg2 arg3, * return void * */ public void callShell(){ try { Runtime rt = Runtime.getRuntime(); rt.exec("/root/shell/test.sh arg1 arg2 arg3"); } catch (IOException e) { e.printStackTrace(); } } /** * 运行shell * * @param shStr 需要执行的shell绝对路径 和参数 * @return echo 打印结果保存在list中,shell中echo值放到list中 * @throws IOException */ public static List runShell(String shStr) throws Exception { List<String> strList = new ArrayList(); Process process; process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null); InputStreamReader ir = new InputStreamReader(process .getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; process.waitFor(); while ((line = input.readLine()) != null){ strList.add(line); System.out.println(line); } return strList; } }