日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁(yè) > 科技  > 軟件

怎么基于Java編寫(xiě)一個(gè)CLI工具?

來(lái)源: 責(zé)編: 時(shí)間:2023-12-11 09:26:18 240觀看
導(dǎo)讀CLICLI,全稱(chēng)為命令行界面(Command Line Interface),是一種用于通過(guò)鍵盤(pán)輸入指令與操作系統(tǒng)進(jìn)行交互的軟件機(jī)制。這種界面是在圖形用戶(hù)界面得到普及之前使用最為廣泛的用戶(hù)界面,并且, 即使在當(dāng)前圖形用戶(hù)界面廣泛使用的環(huán)境

CLI

CLI,全稱(chēng)為命令行界面(Command Line Interface),是一種用于通過(guò)鍵盤(pán)輸入指令與操作系統(tǒng)進(jìn)行交互的軟件機(jī)制。這種界面是在圖形用戶(hù)界面得到普及之前使用最為廣泛的用戶(hù)界面,并且, 即使在當(dāng)前圖形用戶(hù)界面廣泛使用的環(huán)境下,CLI仍然有其獨(dú)特的優(yōu)勢(shì)和廣泛的應(yīng)用。GYu28資訊網(wǎng)——每日最新資訊28at.com

對(duì)于CLI,它的一個(gè)重要特性就是效率。用戶(hù)可以在一條文本命令中對(duì)多個(gè)文件執(zhí)行操作,而不需要在各個(gè)窗口之間切換,節(jié)省了大量時(shí)間。此外,如果你已經(jīng)熟悉了這些命令,那么你可以非常快速地瀏覽系統(tǒng)并與之交互。GYu28資訊網(wǎng)——每日最新資訊28at.com

構(gòu)建CLI的工具很多,今天主要基于Java語(yǔ)言來(lái)實(shí)現(xiàn),其中Apache Commons CLI框架提供了這樣的便利。今天結(jié)合之前學(xué)習(xí)的graalVM提供的native-image工具,來(lái)生成一個(gè)exe類(lèi)型的可執(zhí)行文件,由于graalVM的跨平臺(tái)性,我們還能生成各個(gè)平臺(tái)的CLI命令來(lái)輔助完成更多的工作。GYu28資訊網(wǎng)——每日最新資訊28at.com

Apache Commons CLI是一個(gè)用于編寫(xiě)命令行界面的Java庫(kù)。它提供了一個(gè)靈活的框架,可以很容易地定義和解析命令行參數(shù)。這個(gè)庫(kù)的主要優(yōu)點(diǎn)是它可以處理各種類(lèi)型的參數(shù),包括選項(xiàng)、位置參數(shù)、可選參數(shù)等。GYu28資訊網(wǎng)——每日最新資訊28at.com

構(gòu)成

下面以native-image為例,通過(guò)在終端輸入native-image --help可以看到以下信息GYu28資訊網(wǎng)——每日最新資訊28at.com

_> native-image --helpGraalVM Native Image (https://www.graalvm.org/native-image/)This tool can ahead-of-time compile Java code to native executables.Usage: native-image [options] class [imagename] [options]           (to build an image for a class)   or  native-image [options] -jar jarfile [imagename] [options]           (to build an image for a jar file)   or  native-image [options] -m <module>[/<mainclass>] [options]       native-image [options] --module <module>[/<mainclass>] [options]           (to build an image for a module)where options include:    @argument files       one or more argument files containing options    -cp <class search path of directories and zip/jar files>    -classpath <class search path of directories and zip/jar files>    --class-path <class search path of directories and zip/jar files>                          A ; separated list of directories, JAR archives,                          and ZIP archives to search for class files.    -p <module path>    --module-path <module path>...                          A ; separated list of directories, each directory                          is a directory of modules.

一個(gè)合格的CLI基本都會(huì)提供help選項(xiàng)來(lái)展示,這個(gè)CLI的語(yǔ)法、選項(xiàng)以及功能描述。從上面的輸出可以看到help主要包括:GYu28資訊網(wǎng)——每日最新資訊28at.com

  1. 介紹:主要對(duì)命令的功能的描述,包括官網(wǎng)、版本以及一些內(nèi)在系數(shù)等
  2. 用法:包括命令語(yǔ)法格式、配置項(xiàng)、參數(shù)等信息
  3. 參數(shù)說(shuō)明:具體配置項(xiàng)參數(shù)的說(shuō)明,以及具體的功能描述

Common-CLI

  • 定義階段:在Java代碼中定義Option參數(shù),定義參數(shù)、是否需要輸入值、簡(jiǎn)單的描述等
  • 解析階段:應(yīng)用程序傳入?yún)?shù)后,CLI進(jìn)行解析
  • 詢(xún)問(wèn)階段:通過(guò)查詢(xún)CommandLine詢(xún)問(wèn)進(jìn)入到哪個(gè)程序分支中

定義階段

主要是借助Option類(lèi)提供的API來(lái)構(gòu)建各種選項(xiàng)以及參數(shù)信息,下面是對(duì)應(yīng)API的描述:GYu28資訊網(wǎng)——每日最新資訊28at.com

返回值GYu28資訊網(wǎng)——每日最新資訊28at.com

方法名GYu28資訊網(wǎng)——每日最新資訊28at.com

說(shuō)明GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionsGYu28資訊網(wǎng)——每日最新資訊28at.com

addOption(Option opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

添加一個(gè)選項(xiàng)實(shí)例GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionsGYu28資訊網(wǎng)——每日最新資訊28at.com

addOption(String opt, boolean hasArg, String description)GYu28資訊網(wǎng)——每日最新資訊28at.com

添加一個(gè)只包含短名稱(chēng)的選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionsGYu28資訊網(wǎng)——每日最新資訊28at.com

addOption(String opt, String description)GYu28資訊網(wǎng)——每日最新資訊28at.com

添加一個(gè)只包含短名稱(chēng)的選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionsGYu28資訊網(wǎng)——每日最新資訊28at.com

addOption(String opt, String longOpt, boolean hasArg, String description)GYu28資訊網(wǎng)——每日最新資訊28at.com

添加一個(gè)包含短名稱(chēng)和長(zhǎng)名稱(chēng)的選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionsGYu28資訊網(wǎng)——每日最新資訊28at.com

addOptionGroup(OptionGroup group)GYu28資訊網(wǎng)——每日最新資訊28at.com

添加一個(gè)選項(xiàng)組GYu28資訊網(wǎng)——每日最新資訊28at.com

ListGYu28資訊網(wǎng)——每日最新資訊28at.com

getMatchingOptions(String opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

獲得匹配選項(xiàng)的長(zhǎng)名稱(chēng)集合GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionGYu28資訊網(wǎng)——每日最新資訊28at.com

getOption(String opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

通過(guò)長(zhǎng)名稱(chēng)或短名稱(chēng)獲得選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

OptionGroupGYu28資訊網(wǎng)——每日最新資訊28at.com

getOptionGroup(Option opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

獲得選項(xiàng)所在的選項(xiàng)組GYu28資訊網(wǎng)——每日最新資訊28at.com

CollectionGYu28資訊網(wǎng)——每日最新資訊28at.com

getOptions()GYu28資訊網(wǎng)——每日最新資訊28at.com

獲得一個(gè)只讀的選項(xiàng)集合GYu28資訊網(wǎng)——每日最新資訊28at.com

ListGYu28資訊網(wǎng)——每日最新資訊28at.com

getRequiredOptions()GYu28資訊網(wǎng)——每日最新資訊28at.com

獲得必須的選項(xiàng)集合GYu28資訊網(wǎng)——每日最新資訊28at.com

booleanGYu28資訊網(wǎng)——每日最新資訊28at.com

hasLongOption(String opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

判斷是否存在選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

booleanGYu28資訊網(wǎng)——每日最新資訊28at.com

hasOption(String opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

判斷是否存在選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

booleanGYu28資訊網(wǎng)——每日最新資訊28at.com

hasShortOption(String opt)GYu28資訊網(wǎng)——每日最新資訊28at.com

判斷是否存在選項(xiàng)GYu28資訊網(wǎng)——每日最新資訊28at.com

解析階段

主要對(duì)輸入?yún)?shù)的解析,也就是main方法的參數(shù),默認(rèn)提供下面3中語(yǔ)法解析的支持:GYu28資訊網(wǎng)——每日最新資訊28at.com

  • DefaultParser:提供了基礎(chǔ)的解析功能,能解析簡(jiǎn)單的命令行參數(shù)。(比如:java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • PosixParser:提供了解析POSIX形式參數(shù)的功能。(比如:tar -zxvf foo.tar.gz)
  • GnuParser:提供了解析長(zhǎng)參數(shù)及Java命令中參數(shù)的功能。(比如:du --human-readable --max-depth=1)

詢(xún)問(wèn)階段

基于上一步解析后,會(huì)將參數(shù)解析成CommandLine,結(jié)合Option中的配置,需要我們完成各種配置、參數(shù)匹配后的業(yè)務(wù)處理流程,類(lèi)型下面這樣:GYu28資訊網(wǎng)——每日最新資訊28at.com

if( commandLine.hasOption("help") ){          helper.printHelp("calendar [options] /n/nwhere options include:", null, options, null, false);          return;      }      if( commandLine.hasOption("version") ){          printResult("1.0.0");          return;      }

解析的過(guò)程有時(shí)候會(huì)比較些復(fù)雜,示例中是針對(duì)單一選項(xiàng)的分支,當(dāng)多個(gè)選項(xiàng)混合使用時(shí),比如tar -zxvf xxx.tar.gz這樣的,當(dāng)然前提是我們定義的CLI支持這種風(fēng)格。GYu28資訊網(wǎng)——每日最新資訊28at.com

示例

下面通過(guò)一個(gè)簡(jiǎn)單的示例看下如何構(gòu)建一個(gè)CLI的工具:該示例的作用是按指定格式輸出當(dāng)前日期:GYu28資訊網(wǎng)——每日最新資訊28at.com

clendar -o yyyy-MM-dd
  • 定義配置項(xiàng)
private static Options initOptions() {        Options options = new Options();        options.addOption(Option.builder("H")                .longOpt("help")                .desc("show help information").build());        options.addOption(Option.builder("V")                .longOpt("version")                .desc("show help information").build());        options.addOption(Option.builder("O")                .longOpt("out")                .hasArg(true)                .argName("fmt") // 只是定義                .required(false)                .desc("configure the date output format").build());        return options;    }
  • 解析參數(shù)
private static CommandLine parseArguments(Options options, String[] args){        CommandLineParser parser = new DefaultParser();        try {            return parser.parse(options, args);        } catch (ParseException e) {            System.err.println(e.getMessage());        }        return null;    }
  • 詢(xún)問(wèn)階段
private static void handleCommand(Options options, CommandLine commandLine) {        if(ArrayUtils.isEmpty(commandLine.getOptions()) ){            printResult("Please specify options for calendar building or use --help for more info.");            return;        }        if( commandLine.hasOption("help") ){            helper.printHelp("calendar [options] /n/nwhere options include:", null, options, null, false);            return;        }        if( commandLine.hasOption("version") ){            printResult("1.0.0");            return;        }        if( commandLine.hasOption("out") ){            String fmt = commandLine.getOptionValue("out");            if(StringUtils.isEmpty(fmt)){                fmt = "yyyy-MM-dd HH:mm:ss";            }            printResult(DateFormatUtils.format(new Date(), fmt));            return;        }        // calendar: 'x' is not a git command. See 'calendar --help'.        helper.printHelp(String.format("calendar: '%s' is not a calendar command. See 'calendar --help'.", Arrays.toString(commandLine.getArgs())), options, false);    }

定義程序入口:GYu28資訊網(wǎng)——每日最新資訊28at.com

public static void main(String[] args) {        // 定義階段        Options options = initOptions();        // 解析階段        CommandLine commandLine = parseArguments(options, args);        // 詢(xún)問(wèn)階段        handleCommand(options, commandLine);    }

打包

這里我們引入maven-assembly-plugin插件,主要幫助在打包時(shí)將依賴(lài)包一并寫(xiě)入jar文件,同時(shí)將入口文件定義到manifest:GYu28資訊網(wǎng)——每日最新資訊28at.com

<plugin>    <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-assembly-plugin</artifactId>    <version>3.3.0</version>    <executions>        <execution>            <id>package-jar-with-dependencies</id>            <phase>package</phase>            <goals>                <goal>single</goal>            </goals>            <configuration>                <archive>                    <manifest>                        <mainClass>${main-class}</mainClass>                    </manifest>                </archive>                <descriptorRefs>                    <!-- bin,jar-with-dependencies,src,project -->                    <descriptorRef>jar-with-dependencies</descriptorRef>                </descriptorRefs>            </configuration>        </execution>    </executions></plugin>

可以直接通過(guò)maven插件或者下的命令,將上面的代碼打包成jar文件GYu28資訊網(wǎng)——每日最新資訊28at.com

mvn clean package

測(cè)試jar

如果安裝上面的配置,最終會(huì)在項(xiàng)目target目錄輸出一個(gè)以jar-with-dependencies為后綴的jar文件,通過(guò)下面的命令可以測(cè)試cli命令GYu28資訊網(wǎng)——每日最新資訊28at.com

java -jar ./target/calendar-jar-with-dependencies.jar -h

這樣的CLI可不是我們想要的,一來(lái)需要依賴(lài)JRE的運(yùn)行環(huán)境,同時(shí)調(diào)用極其不方便。GYu28資訊網(wǎng)——每日最新資訊28at.com

生成exe

如果你看過(guò)之前的文章,關(guān)于GraalVM的使用,按照文檔下載并配置好運(yùn)行環(huán)境后,可以通過(guò)下面的命令對(duì)上一步的jar文件進(jìn)一步處理GYu28資訊網(wǎng)——每日最新資訊28at.com

native-image -jar [jar] -o [name]GYu28資訊網(wǎng)——每日最新資訊28at.com

native-image -jar ./target/calendar-jar-with-dependencies.jar -o calendar

通過(guò)上面的命令會(huì)生成一個(gè)calendar.exe文件,這樣將其加入到環(huán)境變量后,則可以在windows平臺(tái)終端上使用了GYu28資訊網(wǎng)——每日最新資訊28at.com

對(duì)于不喜歡直接使用命令的,當(dāng)然這里也可以使用插件exec-maven-plugin,在maven生命周期package階段,自動(dòng)執(zhí)行上面的命令,這樣整個(gè)過(guò)程只需要執(zhí)行mvn clean package即可GYu28資訊網(wǎng)——每日最新資訊28at.com

<plugin>    <groupId>org.codehaus.mojo</groupId>    <artifactId>exec-maven-plugin</artifactId>    <version>3.1.0</version>    <executions>        <execution>            <id>native-image-app</id>            <phase>package</phase>            <goals>                <goal>exec</goal>            </goals>            <configuration>                <environmentVariables>                </environmentVariables>                <!-- native-image -jar ./target/tool-jar-with-dependencies.jar -o tool -->                <executable>native-image</executable>                <arguments>                    <argument>-jar</argument>                    <argument>${project.basedir}/target/${project.build.finalName}-jar-with-dependencies.jar</argument>                    <argument>-o</argument>                    <argument>${project.build.finalName}</argument>                </arguments>            </configuration>        </execution>    </executions></plugin>

測(cè)試exe

在終端執(zhí)行下面的命令接口看到預(yù)期的結(jié)果:GYu28資訊網(wǎng)——每日最新資訊28at.com

calendar.exe -O yyyy-MM-dd

總結(jié)

總的來(lái)說(shuō),Apache Commons CLI是一個(gè)非常強(qiáng)大的工具,可以幫助你輕松地處理命令行參數(shù)。無(wú)論你的應(yīng)用程序需要處理多少個(gè)參數(shù),或者這些參數(shù)的類(lèi)型是什么, Commons CLI都可以提供幫助。GYu28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-41684-0.html怎么基于Java編寫(xiě)一個(gè)CLI工具?

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: Go語(yǔ)言 字符串拼接方式與性能比較,分析過(guò)沒(méi)?

下一篇: Spring6提供的四種遠(yuǎn)程接口調(diào)用神器!你知道那種?

標(biāo)簽:
  • 熱門(mén)焦點(diǎn)
Top 主站蜘蛛池模板: 纳雍县| 容城县| 丹巴县| 长丰县| 灵丘县| 微博| 嘉禾县| 榆社县| 镇远县| 沈阳市| 西乡县| 咸阳市| 台山市| 合阳县| 宕昌县| 砀山县| 台北县| 临朐县| 扎兰屯市| 大安市| 广平县| 射阳县| 化州市| 靖州| 镇原县| 宁河县| 田东县| 定陶县| 龙胜| 德兴市| 徐水县| 元阳县| 禄劝| 定日县| 大荔县| 龙陵县| 山东省| 临海市| 阜康市| 壶关县| 琼海市|