Java 調(diào)用 shell 命令

雖然說(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)日后再行研究
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末醉拓,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子收苏,更是在濱河造成了極大的恐慌亿卤,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件鹿霸,死亡現(xiàn)場(chǎng)離奇詭異排吴,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)懦鼠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)钻哩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)屹堰,“玉大人,你說(shuō)我怎么就攤上這事街氢〕都” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵珊肃,是天一觀的道長(zhǎng)荣刑。 經(jīng)常有香客問(wèn)我,道長(zhǎng)近范,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任延蟹,我火速辦了婚禮评矩,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘阱飘。我一直安慰自己斥杜,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布沥匈。 她就那樣靜靜地躺著蔗喂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪高帖。 梳的紋絲不亂的頭發(fā)上缰儿,一...
    開(kāi)封第一講書(shū)人閱讀 51,590評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音散址,去河邊找鬼乖阵。 笑死,一個(gè)胖子當(dāng)著我的面吹牛预麸,可吹牛的內(nèi)容都是我干的瞪浸。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼吏祸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼对蒲!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起贡翘,我...
    開(kāi)封第一講書(shū)人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤蹈矮,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后鸣驱,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體含滴,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年丐巫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了谈况。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片勺美。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖碑韵,靈堂內(nèi)的尸體忽然破棺而出赡茸,到底是詐尸還是另有隱情,我是刑警寧澤祝闻,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布占卧,位于F島的核電站,受9級(jí)特大地震影響联喘,放射性物質(zhì)發(fā)生泄漏华蜒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一豁遭、第九天 我趴在偏房一處隱蔽的房頂上張望叭喜。 院中可真熱鬧,春花似錦蓖谢、人聲如沸捂蕴。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)啥辨。三九已至,卻和暖如春盯腌,著一層夾襖步出監(jiān)牢的瞬間溉知,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工腕够, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留着倾,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓燕少,卻偏偏與公主長(zhǎng)得像卡者,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子客们,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容