標籤:pre 4.4 generic ror tran 網上 orm exit rip
有些時候會碰到這樣的情境: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 ms64 bytes from localhost (111.13.100.91): icmp_seq=2 ttl=52 time=7.90 ms64 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 2003msrtt min/avg/max/mdev = 7.668/9.861/14.013/2.937 ms
總結
Java 執行指令碼的方式其實類似用直接在bash裡面執行指令碼,區別在於環境有些變動,執行的效果和bash基本一致。
本文發佈於公眾號:可樂小資料(xiaokele_data)。
Java如何調用shell指令碼的