2023年7月13日发(作者:)
java命令⾏参数解析_Java中命令⾏参数解析 Apache Commons CLI library provides an API for parsing command line options passed to programs. It's also able toprint help messages detailing the options available for a command line s CLI supports different types of options:POSIX like options (ie. tar -zxvf )GNU like long options (ie. du --human-readable --max-depth=1)Java like properties ( -ss=true -temProxies=true Foo)Short options with value attached (ie. gcc -O2 foo.c)long options with single hyphen (ie. ant -projecthelp)Maven仓库commons-clicommons-cli1.3Example:如果想要得到下⾯的⼀个参数列表:java wordcount [-help] [-O][value] [-c] otherfilename//演⽰使⽤的是1.3的版本public static void main(String[] args) throws IOException, ParseException {//option的容器Options options = new Options();//boolean型的ion("help",false,"help information");//当第⼆参数是true时,可以是这样的参数 -ion("O",true,"you can set a value after the O");Option c = r("c") //option的名字,判断的时候要使⽤这个名字.required(false) //是否必须有这个选项.hasArg() //带⼀个参数.argName("filename") //参数的名字.desc("return sum of characters") //描述.build(); //必须有//将c这个option添加进去ion(c);//parserCommandLineParser parser = new DefaultParser();CommandLine cmd = (options,args);//询问是否有helpif(ion("help")) {//调⽤默认的help函数打印HelpFormatter formatter = new HelpFormatter();elp( "java wordcount [OPTION] ", options );return;}if(ion("c")){// 获得相应的选项(c)的参数String filename = ionValue("c");n(filename);// do something}//将除了选项之外的参数打印出来 otherfilenameString[] s = s();for(String e : s){n("="+e);}PS:⾃⼰的CommandLine Parser即是Scanner疑惑Option c = r("c") //option的名字 貌似没什么卵⽤?.required(false) //是否必须有这个选项.hasArg() //带⼀个参数.argName("filename") //参数的名字.desc("return sum of characters") //描述.build(); //必须有为什么创建Option的时候要⽤⼀个build这样⼀个中间的类来创建,不直接使⽤new之类的关键字创建不是更好吗?反正我看了⼀下build()函数也只是将属性直接赋值过去⽽已?是⽤了什么设计模式吗?还是为了安全考虑?其实最后还是内部给new出来了不是吗?public Option build(){if (opt == null && longOpt == null){throw new IllegalArgumentException("Either opt or longOpt must be specified");}return new Option(this);}然后就是直接复制过去,其实完全可以将Builder中的⼀些函数给Option中,不是吗?private Option(final Builder builder){e = e;ption = ption;t = t;OfArgs = OfArgs; = ;alArg = alArg;ed = ed; = ;ep = ep;}参考
发布者:admin,转转请注明出处:http://www.yc00.com/news/1689198693a219818.html
评论列表(0条)