Commons Cli 简明教程

Apache Commons CLI - Argument Option

在命令行中,参数选项由其名称及其相应的值表示。例如,如果存在选项,那么用户必须传递其值。考虑以下示例,如果我们将日志输出到某个文件,为此,我们希望用户使用参数选项 logFile 输入日志文件的名称。

An Argument option is represented on a command line by its name and its corresponding value. For example, if option is present, then user has to pass its value. Consider the following example, if we are printing logs to some file, for which, we want user to enter name of the log file with the argument option logFile.

Example

CLITester.java

CLITester.java

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CLITester {
   public static void main(String[] args) throws ParseException {
      Options options = new Options();
      Option logfile = Option.builder()
         .longOpt("logFile")
         .argName("file" )
         .hasArg()
         .desc("use given file for log" )
         .build();

      options.addOption(logfile);
      CommandLineParser parser = new DefaultParser();
      CommandLine cmd = parser.parse( options, args);

      // has the logFile argument been passed?
      if(cmd.hasOption("logFile")) {
         //get the logFile argument passed
         System.out.println( cmd.getOptionValue( "logFile" ) );
      }
   }
}

Output

在将 --logFile 作为选项传递的同时运行该文件,将该文件的名称作为该选项的值,然后查看结果。

Run the file, while passing --logFile as option, name of the file as value of the option and see the result.

java CLITester --logFile test.log
test.log