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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章