public class CommandUtil { /** * 在指定路径下执行一条命令,不能执行cd之类的命令 * * @param command 要执行的Linux命令 * @param dir 目标路径,在该路径执行上述Linux命令 * @return 命令执行后显示的结果 * @throws IOException */ public static String run(String command, File dir) throws IOException { Scanner input = null; StringBuilder result = new StringBuilder(command + "\n"); // 加上命令本身 Process process = null; try { process = Runtime.getRuntime().exec(command, null, dir); try { //等待命令执行完成 process.waitFor(10, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } InputStream is = process.getInputStream(); input = new Scanner(is); while (input.hasNextLine()) { result.append(input.nextLine() + "\n"); } } finally { if (input != null) { input.close(); } if (process != null) { process.destroy(); } } return result.toString(); } /** * 在指定路径下,开启脚本,可以执行多条命令 * * @param command 要执行的Linux命令 * @param dir 目标路径,在该路径执行上述Linux命令 * @return 所有命令执行后显示的结果 * @throws IOException */ public static List<String> run(String[] command, File dir) throws IOException { BufferedReader in = null; PrintWriter out = null; List<String> resultList = new ArrayList<String>(); Process process = null; try { // 开启脚本是为了能够获取所有的返回结果 process = Runtime.getRuntime().exec("/bin/sh", null, dir); // /bin/sh开启shell脚本 in = new BufferedReader(new InputStreamReader(process.getInputStream())); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true); for (String cmd : command) { out.println(cmd); // 一条条执行命令 } out.println("exit"); // 表示脚本结束,必须执行,否则in流不结束。 try { // 等待命令执行完成 process.waitFor(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } // 装填返回结果,比如ls命令执行后显示的一行行字符串 String line = ""; while ((line = in.readLine()) != null) { resultList.add(line); } resultList.add(0, Arrays.toString(command)); // 加上命令本身,可根据需要自行取舍 } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } if (process != null) { process.destroy(); } } return resultList; }
测试
public static void main(String[] args) throws IOException { String jarCommand = "mvn clean package -T 1C -Dmaven.test.skip=true -Dmaven.compile.fork=true"; // 打包命令,忽略测试类 System.out.println(run(jarCommand, new File("/Users/code/other/master"))); }
标签:语句,java,process,命令,command,linux,new,null,out From: https://www.cnblogs.com/action1/p/17350720.html