雖然說(shuō)在一種語(yǔ)言里面東拉西扯地調(diào)用其他語(yǔ)言有些異類(lèi)囱嫩,但是不容質(zhì)疑的是恃疯,每種語(yǔ)言都有其優(yōu)勢(shì)之處,揚(yáng)長(zhǎng)避短總是明智的選擇墨闲。
shell 的大部分命令是用 C 語(yǔ)言實(shí)現(xiàn)的今妄,所以二進(jìn)制代碼執(zhí)行速度是 java 等高級(jí)語(yǔ)言無(wú)法望其項(xiàng)背的。
在 linux 平臺(tái)下不能忘記強(qiáng)大的系統(tǒng)自帶屬性--shell.
之前用到的命令 sed
,awk
十分強(qiáng)大鸳碧,在文本處理時(shí)可以從速度和操作便捷秒殺Java盾鳞。
測(cè)試一下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author: kent
* @date: 2018/5/10 21:11
*/
public class TestShell {
public static void main(String[] args) {
Process process;
try {
process = Runtime.getRuntime().exec("grep grep /Users/kent/.bash_history");//查看我的 .bash_history里面的grep 命令使用歷史記錄
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
int exitValue = process.waitFor();
while((line = reader.readLine())!= null){
System.out.println(line);
}
if (exitValue == 0){
System.out.println( "successfully executed the linux command");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
調(diào)用還是比較便捷的。
來(lái)看一下JDK中的Runtime的源碼
/**Runtime類(lèi)型說(shuō)明
* Every Java application has a single instance of class
每一個(gè)Java應(yīng)用都有一個(gè)允許應(yīng)用與運(yùn)行環(huán)境交互的Runtime單實(shí)例瞻离,當(dāng)前的運(yùn)行環(huán)境可以通過(guò)getRuntime方法獲得
* <code>Runtime</code> that allows the application to interface with
* the environment in which the application is running. The current
* runtime can be obtained from the <code>getRuntime</code> method.
* <p>
* An application cannot create its own instance of this class.
應(yīng)用里面無(wú)法創(chuàng)建該類(lèi)型的實(shí)例腾仅,后面可以發(fā)現(xiàn)構(gòu)造方法被 private修飾了
* @author unascribed
* @see java.lang.Runtime#getRuntime()
* @since JDK1.0
*/
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*返回當(dāng)前運(yùn)行環(huán)境
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class不允許其他人初始化該類(lèi)型 */
private Runtime() {}
最核心的運(yùn)行方法 exec:
/**
* Executes the specified command and arguments in a separate process with
* the specified environment and working directory.
*在一個(gè)單獨(dú)的Process里面運(yùn)行聲明環(huán)境和運(yùn)行路徑的指定命令和參數(shù)
* <p>Given an array of strings <code>cmdarray</code>, representing the
* tokens of a command line, and an array of strings <code>envp</code>,
* representing "environment" variable settings, this method creates
* a new process in which to execute the specified command.
* 一組字符串cmdArray代表的是命令行,一組字符串envp代表環(huán)境變量套利,該方法可以創(chuàng)建一個(gè)運(yùn)行指定命令的process
* <p>This method checks that <code>cmdarray</code> is a valid operating
* system command. Which commands are valid is system-dependent,
* but at the very least the command must be a non-empty list of
* non-null strings.
*該方法檢查cmdArray 是明確的操作系統(tǒng)命令推励。至于什么樣的命令是明確的則取決于操作系統(tǒng)。
* <p>If <tt>envp</tt> is <tt>null</tt>, the subprocess inherits the
* environment settings of the current process.
*如果envp為空肉迫,子process繼承當(dāng)前process的環(huán)境設(shè)置
* <p>A minimal set of system dependent environment variables may
* be required to start a process on some operating systems.
* As a result, the subprocess may inherit additional environment variable
* settings beyond those in the specified environment.
*
* <p>{@link ProcessBuilder#start()} is now the preferred way to
* start a process with a modified environment.
*
* <p>The working directory of the new subprocess is specified by <tt>dir</tt>.dir指定子Process的工作目錄
* If <tt>dir</tt> is <tt>null</tt>, the subprocess inherits the
* current working directory of the current process.
*
* <p>Starting an operating system process is highly system-dependent.
* Among the many things that can go wrong are:
* <ul>啟動(dòng)操作系統(tǒng)進(jìn)程高度依賴于操作系統(tǒng)吹艇,所以以下地方可能出錯(cuò)
* <li>The operating system program file was not found.操作系統(tǒng)程序未找到
* <li>Access to the program file was denied.程序禁止訪問(wèn)
* <li>The working directory does not exist.工作目錄不存在
* </ul>
*
* <p>In such cases an exception will be thrown. The exact nature
* of the exception is system-dependent, but it will always be a
* subclass of {@link IOException}.
*不同系統(tǒng)拋出異常的根本原因可能不同,但是異嘲悍鳎總是IOException的子類(lèi)
*
* @param cmdarray array containing the command to call and
* its arguments.
* 調(diào)用的命令以及其參數(shù)
* @param envp array of strings, each element of which
* has environment variable settings in the format
* <i>name</i>=<i>value</i>, or
* <tt>null</tt> if the subprocess should inherit
* the environment of the current process.
*環(huán)境變量受神,子進(jìn)程會(huì)繼承父進(jìn)程的環(huán)境
* @param dir the working directory of the subprocess, or
* <tt>null</tt> if the subprocess should inherit
* the working directory of the current process.
*子進(jìn)程工作目錄
* @return A new {@link Process} object for managing the subprocess
*
* @throws SecurityException
* If a security manager exists and its
* {@link SecurityManager#checkExec checkExec}
* method doesn't allow creation of the subprocess
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>cmdarray</code> is <code>null</code>,
* or one of the elements of <code>cmdarray</code> is <code>null</code>,命令為空以及環(huán)境變量為空導(dǎo)致空指針異常
* or one of the elements of <code>envp</code> is <code>null</code>
*
* @throws IndexOutOfBoundsException
* If <code>cmdarray</code> is an empty array命令為空會(huì)導(dǎo)致數(shù)組越界異常
* (has length <code>0</code>)
*
* @see ProcessBuilder
* @since 1.3
*/
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}
還有一些方法可以返回jvm的內(nèi)存參數(shù)
這些方法比較底層
再看以下Process類(lèi)型的源碼
process是一個(gè)抽象類(lèi),用于創(chuàng)建一個(gè)子進(jìn)程格侯,執(zhí)行系統(tǒng)命令鼻听。可以對(duì)接Runtime中的exec方法返回一個(gè)process實(shí)例联四。
image.png
這些抽象方法的具體實(shí)現(xiàn)取決于操作系統(tǒng)撑碴,不同的系統(tǒng)下其子類(lèi)不同,unix平臺(tái)下對(duì)應(yīng)的是UNIXProcess類(lèi)朝墩。
UNIXProcess類(lèi)日后再行研究