使用 commons-cli 處理命令行參數
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 ;
} //繼續執行程序代碼 }</pre>
看看上面程序中,使用方法非常簡單,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