使用 commons-cli 处理命令行参数

12年前
Commons CLI 是一个用来处理命令行参数的 Java 工具包。

看下面这段代码:
/**   * 程序入口   * @param args   * @throws ParseException    */  public static void main(String[] args) throws IOException, ParseException {   // create the Options   Options options = new Options();   options.addOption( "s", "src", true, "source folder" );   options.addOption( "d", "dest", true, "destination folder" );   options.addOption( "l", "log", false, "building log file path");        CommandLineParser parser = new PosixParser();   CommandLine cmd = parser.parse(options, args);   String log_file_path = cmd.getOptionValue('l');   String src_path = cmd.getOptionValue('s');   String dest_path = cmd.getOptionValue('d');      if(StringUtils.isBlank(src_path) || StringUtils.isBlank(dest_path)) {    HelpFormatter formatter = new HelpFormatter();    formatter.printHelp( "check_build", options );    return ;   }   //继续执行程序代码  }

看看上面程序中,使用方法非常简单,Options 对象可用于格式化输出命令的帮助信息。

最终执行结果:

D:\WORKDIR\xxxx>check_build  usage: check_build   -d,--dest <arg>   destination folder   -l,--log          building log file path   -s,--src <arg>    source folder