Java執行shell腳本並返回結果兩種方法的完整代碼


https://www.cnblogs.com/zdz8207/p/java-linux-shell.html

Java執行shell腳本並返回結果兩種方法的完整代碼

簡單的是直接傳入String字符串,這種不能執行echo 或者需要調用其他進程的命令(比如調用postfix發送郵件命令就不起作用)

執行復雜的shell建議使用String[]方式傳遞(對外可以封裝后也傳入String字符串)。

 

復制代碼
/**
     * 運行shell腳本
     * @param shell 需要運行的shell腳本
     */
    public static void execShell(String shell){
        try {
            Runtime.getRuntime().exec(shell);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 運行shell腳本 new String[]方式
     * @param shell 需要運行的shell腳本
     */
    public static void execShellBin(String shell){
        try {
            Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shell},null,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
 
    /**
     * 運行shell並獲得結果,注意:如果sh中含有awk,一定要按new String[]{"/bin/sh","-c",shStr}寫,才可以獲得流
     * 
     * @param shStr
     *            需要執行的shell
     * @return
     */
    public static List<String> runShell(String shStr) {
        List<String> strList = new ArrayList<String>();
        try {
            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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strList;
    }
復制代碼

 

大自然,飄然的風,QQ群: python技術交流群:453879716,人工智能深度學習群:251088643
golang技術交流群:316397059,vuejs技術交流群:458915921 有興趣的可以加入
微信公眾號:大自然預測(ssqyuce)原雙色球預測, 心禪道(xinchandao),囤幣一族(tunbitt)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM