java解析命令行参数(common-cli)

Java代码    收藏代码
  1. import org.apache.commons.cli.CommandLineParser;  
  2. import org.apache.commons.cli.BasicParser;  
  3. import org.apache.commons.cli.Options;  
  4. import org.apache.commons.cli.CommandLine;  
  5.   
  6. public static void main(String[] args) throws Exception {  
  7.   // Create a Parser  
  8.   CommandLineParser parser = new BasicParser( );  
  9.   Options options = new Options( );  
  10.   options.addOption("h""help"false"Print this usage information");  
  11.   options.addOption("v""verbose"false"Print out VERBOSE information" );  
  12.   options.addOption("f""file"true"File to save program output to");  
  13.   // Parse the program arguments  
  14.   CommandLine commandLine = parser.parse( options, args );  
  15.   // Set the appropriate variables based on supplied options  
  16.   boolean verbose = false;  
  17.   String file = "";  
  18.    
  19.   if( commandLine.hasOption('h') ) {  
  20.     System.out.println( "Help Message")  
  21.     System.exit(0);  
  22.   }  
  23.   if( commandLine.hasOption('v') ) {  
  24.     verbose = true;  
  25.   }  
  26.   if( commandLine.hasOption('f') ) {  
  27.     file = commandLine.getOptionValue('f');  
  28.   }  
  29. }  

 

 

上面是代码片段使用方法:

 

java xxxx -h

java xxxx -f 119

 

代码摘录:

http://www.discursive.com/books/cjcook/reference/app-infra-sect-parsing-simple-cmdline

你可能感兴趣的:(java)