最近学习mahout的时候需要编译打包,然后在命令行运行程序,一般来说自己调试程序的话输入参数自己都是知道的,比较好设置比如你可以自己定义args[0] 是input,args[1]是output,但是如果其他人看你的程序的话,就很难搞懂哪个参数是对应的哪个。最近看到一个类Options和Option、CommandLine,这几个类可以提供一种参数输入错误的提示,而且比较好用,下面贴下一个使用demo:
package org.fansy.date1030.hbase.in.action.chapter7;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
public class CommendLineDemo{
/**
* to define the parameters
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
CommandLine cmd=parseArgs(args);
String input=cmd.getOptionValue("i");
String output=cmd.getOptionValue("o");
String optional=null;
if(cmd.hasOption("optional")){
optional=cmd.getOptionValue("optional");
}
System.out.println("input:"+input+",output:"+output+",optional:"+optional);
}
public static CommandLine parseArgs(String[] args)throws ParseException{
Options options=new Options();
// input
Option o=new Option("i","inputPath",true,"file input path should exist");
o.setArgName("input-path");
o.setRequired(true);
options.addOption(o);
// output
o=new Option("o","outputPath",true,"file output path should exist");
o.setArgName("output-path");
o.setRequired(true);
options.addOption(o);
// optional
o=new Option("optional","optional",true,"this is an optional choice");
o.setArgName("optional");
o.setRequired(false);
options.addOption(o);
CommandLineParser parser=new PosixParser();
CommandLine cmd=null;
try{
cmd=parser.parse(options, args);
}catch(Exception e){
System.err.println("ERROR:"+e.getMessage()+"\n");
HelpFormatter formatter =new HelpFormatter();
formatter.printHelp("set args demo: ", options,true);
System.exit(-1);
}
return cmd;
}
}
Option类的参数说明:
public Option(String opt,
String longOpt,
boolean hasArg,
String description)
throws IllegalArgumentException
Creates an Option using the specified parameters.
Parameters:
opt - short representation of the option
longOpt - the long representation of the option
hasArg - specifies whether the Option takes an argument or not
description - describes the function of the option
Mark