這是一個處理處理命令的工具。比如main方法輸入的string[]需要解析。你可以預先定義好參數的規則,然後就可以調用CLI來解析。
下載地址:http://commons.apache.org/downloads/download_cli.cgi
如下為使用cli生成命令行注釋的演示代碼:
package demo;
上訴代碼運行後在控制台輸入 -h,顯示如下信息:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class OptionsTip ...{
public static void main(String[] args) ...{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
try ...{
args = in.readLine().split(" ");
Options opt = new Options();
opt.addOption("h", false, "Print help for this application");
opt.addOption("u", true, "The username to use");
opt.addOption("dsn", true, "The data source to use");
BasicParser parser = new BasicParser();
CommandLine cl = parser.parse(opt, args);
if (cl.hasOption('h')) ...{
HelpFormatter f = new HelpFormatter();
f.printHelp("OptionsTip", opt);
} else ...{
System.out.println(cl.getOptionValue("u"));
System.out.println(cl.getOptionValue("dsn"));
}
} catch (ParseException e) ...{
e.printStackTrace();
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
usage: OptionsTip
-dsn <arg> The data source to use
-h Print help for this application
-u <arg> The username to use