Java执行Linux命令

转载地址

最近工作中需要在Java中执行Linux命令,对遇到的坑做一个小结。
API
把要执行的命令作为exec方法的参数,返回一个Process对象代表命令执行的进程。由于执行完命令通常要获取输出显示出来,因此对执行命令并获取输出的过程封装为一个工具类:
 

CommandUtil

    package org.ml.deployer.util;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Scanner;
    import java.util.concurrent.TimeUnit;
     
    public class CommandUtil {
        public static String run(String command) throws IOException {
            Scanner input = null;
            String result = "";
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(command);
                try {
                    //等待命令执行完成
                    process.waitFor(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                InputStream is = process.getInputStream();
                input = new Scanner(is);
                while (input.hasNextLine()) {
                    result += input.nextLine() + "\n";
                }
                result = command + "\n" + result; //加上命令本身,打印出来
            } finally {
                if (input != null) {
                    input.close();
                }
                if (process != null) {
                    process.destroy();
                }
            }
            return result;
        }
        
        public static String run(String[] command) throws IOException {
            Scanner input = null;
            String result = "";
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(command);
                try {
                    //等待命令执行完成
                    process.waitFor(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                InputStream is = process.getInputStream();
                input = new Scanner(is);
                while (input.hasNextLine()) {
                    result += input.nextLine() + "\n";
                }
                result = command + "\n" + result; //加上命令本身,打印出来
            } finally {
                if (input != null) {
                    input.close();
                }
                if (process != null) {
                    process.destroy();
                }
            }
            return result;
        }
    }

示例:

执行启动tomcat的脚本:


执行结果:


执行带特殊字符的命令

exec方法无法执行带 | > 等特殊字符的命令,如 ps -ef | grep java 。

此时要把整个命令作为 /bin/sh 的参数执行,如:


注意

exec方法通过创建一个子进程执行Linux命令,因此频繁地通过Java调用Linux命令对性能影响非常大,不要在程序中过度使用这种方式。

发布了48 篇原创文章 · 获赞 23 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章