Java如何調用shell腳本的


有些時候會碰到這樣的場景:java的功能里面要嵌入一個功能點,這個功能是通過是shell腳本實現的。這種時候就需要Java對腳本調用的支持了。

測試環境

Ubuntu16.04 i3-6100,12GB

Hello World

來看一個基本的例子

    Process exec = Runtime.getRuntime().exec(new String[] { "uname" ,"-a"});
    exec.waitFor();
    BufferedReader reader =
            new BufferedReader(new InputStreamReader(exec.getInputStream()));
    System.out.println(reader.readLine());

Linux jason-Inspiron-3650 4.4.0-121-generic #145-Ubuntu SMP Fri Apr 13 13:47:23 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

解讀Process

java.lang.Process類提供了獲取輸入、輸出、等待執行和銷毀進程的方法。
Process類可通過ProcessBuilder.start() 和 Runtime.exec 創建實例,從Java1.5開始,ProcessBuilder.start()是更推薦的做法,但網上的教程更多推薦用Runtime.exec()方法。

Modifier and Type Method Description
abstract void destroy () Kills the subprocess.
abstract int exitValue () Returns the exit value for the subprocess.
abstract InputStream getErrorStream () Returns the input stream connected to the error output of the subprocess.
abstract InputStream getInputStream () Returns the input stream connected to the normal output of the subprocess.
abstract OutputStream getOutputStream () Returns the output stream connected to the normal input of the subprocess.
abstract int waitFor () Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

繼承體系上面,Process的實現類是JDK內置的,linux版本的jdk中只帶有一個實現類UnixProcess。

與腳本交互

Process不但可以執行進程,還可以獲取進程的返回結果。

    private String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            int exitCode = p.waitFor();
            System.out.println(exitCode);
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(output.toString());
        return output.toString();
    }

PING www.a.shifen.com (111.13.100.91) 56(84) bytes of data.
64 bytes from localhost (111.13.100.91): icmp_seq=1 ttl=52 time=7.66 ms
64 bytes from localhost (111.13.100.91): icmp_seq=2 ttl=52 time=7.90 ms
64 bytes from localhost (111.13.100.91): icmp_seq=3 ttl=52 time=14.0 ms

--- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 7.668/9.861/14.013/2.937 ms

總結

Java 執行腳本的方式其實類似用直接在bash里面執行腳本,區別在於環境有些變動,執行的效果和bash基本一致。

本文發布於微信公眾號:可樂小數據(xiaokele_data)。


免責聲明!

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



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