频道栏目
首页 > 资讯 > Java > 正文

Java命令行参数解析_Java命令行参数开发实例

17-12-15        来源:[db:作者]  
收藏   我要投稿

Java命令行参数解析_Java命令行参数开发实例。

import org.apache.commons.cli.CommandLineParser;  

import org.apache.commons.cli.BasicParser;  

import org.apache.commons.cli.Options;  

import org.apache.commons.cli.CommandLine;  

  

publicstaticvoid main(String[] args) throws Exception {  

  // Create a Parser  

  CommandLineParser parser = new BasicParser( );  

  Options options = new Options( );  

  options.addOption("h", "help", false, "Print this usage information");  

  options.addOption("v", "verbose", false, "Print out VERBOSE information" );  

  options.addOption("f", "file", true, "File to save program output to");  

  // Parse the program arguments  

  CommandLine commandLine = parser.parse( options, args );  

  // Set the appropriate variables based on supplied options  boolean verbose = false;  

  String file = "";  

   

  if( commandLine.hasOption('h') ) {  

    System.out.println( "Help Message")  

    System.exit(0);  

  }  

  if( commandLine.hasOption('v') ) {  

    verbose = true;  

  }  

  if( commandLine.hasOption('f') ) {  

    file = commandLine.getOptionValue('f');  

  }  

commons-clicommons-cli1.2

熟悉Linux命令的都知道几乎所有程序都会提供一些命令行选项。而命令行选项有两种风格:以“-”开头的单个字符的POSIX风格;以“--”后接选项关键字的GNU风格。 

假定我们的程序需要以下选项: 

引用

Options: 

  -t,--text use given information(String) 

  -b display current time(boolean) 

  -s,--size use given size(Integer) 

  -f,--file use given file(File) 

  -D  use value for given property(property=value)

 

(1)Apache的Commons-CLI

版本:commons-cli-1.2.jar 

支持三种CLI选项解析: 

BasicParser:直接返回参数数组值

PosixParser:解析参数及值(-s10)

GnuParser:解析参数及值(--size=10)

对于动态参数: 

-Dkey=value 

需要代码设置参数,返回类型需要转换。 

Java代码  

args = new String[]{"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s10", "-Dkey1=value1", "-Dkey2=value2" };  

  

try {  

    // create Options object  

    Options options = new Options();  

    options.addOption(new Option("t", "text", true, "use given information(String)"));  

    options.addOption(new Option("b", false, "display current time(boolean)"));  

    options.addOption(new Option("s", "size", true, "use given size(Integer)"));  

    options.addOption(new Option("f", "file", true, "use given file(File)"));  

  

    @SuppressWarnings("static-access")  

    Option property = OptionBuilder.withArgName("property=value")  

            .hasArgs(2)  

            .withValueSeparator()  

            .withDescription("use value for given property(property=value)")  

            .create("D");  

    property.setRequired(true);  

    options.addOption(property);  

  

    // print usage  

    HelpFormatter formatter = new HelpFormatter();  

    formatter.printHelp( "AntOptsCommonsCLI", options );  

    System.out.println();  

  

    // create the command line parser  

    CommandLineParser parser = new PosixParser();  

    CommandLine cmd = parser.parse(options, args);  

  

    // check the options have been set correctly  

    System.out.println(cmd.getOptionValue("t"));  

    System.out.println(cmd.getOptionValue("f"));  

    if (cmd.hasOption("b")) {  

        System.out.println(new Date());  

    }  

    System.out.println(cmd.getOptionValue( "s" ));  

    System.out.println(cmd.getOptionProperties("D").getProperty("key1") );  

    System.out.println(cmd.getOptionProperties("D").getProperty("key2") );  

      

} catch (Exception ex) {  

    System.out.println( "Unexpected exception:" + ex.getMessage() );  

 

(2)Args4J

版本:args4j-2.0.29.jar 

基于注解。 

Java代码  

args = new String[] {"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s", "10", "-D", "key1=value1" , "-D", "key2=value2"};  

  

try {  

    Args4jOptions options = new Args4jOptions();  

    CmdLineParser parser = new CmdLineParser(options);  

  

    // print usage      parser.printUsage(System.out);  

    System.out.println();  

  

    parser.parseArgument(args);  

      

    // check the options have been set correctly      System.out.println(options.getText());    

    System.out.println(options.getFile().getName());          

    if(options.isBol()) {  

        System.out.println(new Date());  

    }             

    System.out.println(options.getSize());  

    System.out.println(options.getProperties().get("key1"));  

    System.out.println(options.getProperties().get("key2"));  

  

} catch (Exception ex) {  

    System.out.println("Unexpected exception:" + ex.getMessage());  

}  

Java代码  

@Option(name = "-t", aliases = "-text", usage = "use given information(String)")  

private String text;  

@Option(name = "-b", usage = "display current time(boolean)")  

privateboolean bol = false;  

@Option(name = "-s", aliases = "-size", usage = "use given size(Integer)")  

privateint size = 0;  

@Option(name = "-f", aliases = { "-file" }, metaVar = "", usage = "use given file(File)")  

private File file;  

  

private Map properties = new HashMap();  

@Option(name = "-D", metaVar = "=", usage = "use value for given property(property=value)")  

publicvoid setProperty(final String property) {  

    String[] arr = property.split("=");  

    properties.put(arr[0], arr[1]);  

}  

 

(3)JCommander

版本:jcommander-1.45.jar 

基于注解、TestNG作者开发。 

Java代码  

args = new String[] {"-t", "rensanning", "-f", "c:/aa.txt", "-b", "-s", "10", "-D", "key1=value1" , "-D", "key2=value2"};  

  

try {  

    JCmdrOptions options = new JCmdrOptions();  

    JCommander jcmdr = new JCommander(options, args);  

  

    // print usage  

    jcmdr.setProgramName("AntOptsCommonsCLI");  

    jcmdr.usage();  

  

    // check the options have been set correctly      System.out.println(options.getText());    

    System.out.println(options.getFile().getName());          

    if(options.isBol()) {  

        System.out.println(new Date());  

    }             

    System.out.println(options.getSize());  

    System.out.println(options.getDynamicParams().get("key1"));  

    System.out.println(options.getDynamicParams().get("key2"));  

  

} catch (Exception ex) {  

    System.out.println("Unexpected exception:" + ex.getMessage());  

}  

Java代码  

 1 @Parameter(names = { "-t", "-text" }, description = "use given information(String)")  

 2private String text;  

 3 @Parameter(names = { "-b" }, description = "display current time(boolean)")  

 4privateboolean bol = false;  

 5 @Parameter(names = { "-s", "-size" }, description = "use given size(Integer)")  

 6privateint size = 0;  

 7 @Parameter(names = { "-f", "-file" }, description = "use given file(File)")  

 8private File file;  

 9 @DynamicParameter(names = "-D", description = "use value for given property(property=value)")  

10public Map dynamicParams = new HashMap(); 

相关TAG标签
上一篇:win7系统添加网络打印机的方法步骤
下一篇:eclipse命令行参数_eclipse输入命令行参数详解
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站