Java构建命令行启动模式CommandLineParser/Options

public void parseArgs(String[] args) throws ParseException {
    // Create a Parser
    CommandLineParser parser = new BasicParser( );
    Options options = new Options( );
    options.addOption("h", "help", false, "Print this usage information");
    options.addOption("c", "cfg", true, "config Absolute Path");
    options.addOption("l", "log", true, "log configuration");

    // Parse the program arguments
    CommandLine commandLine = parser.parse( options, args );
    // Set the appropriate variables based on supplied options

    if( commandLine.hasOption('h') ) {
        printHelpMessage();
        System.exit(0);
    }
    if( commandLine.hasOption('c') ) {
        cfg = new File(commandLine.getOptionValue('c'));
    } else {
        printHelpMessage();
        System.exit(0);
    }
    if( commandLine.hasOption('l') ) {
        log = new File(commandLine.getOptionValue('l'));
    } else {
        printHelpMessage();
        System.exit(0);
    }
}
public void printHelpMessage() {
    System.out.println( "Change the xml File and Log.XML Path to the right Absolute Path base on your project Location in your computor");
    System.out.println("Usage example: ");
    System.out.println( "java -cfg D:\\MyProject\\face2face\\logic\\src\\main\\resources\\logic.xml  -log D:\\MyProject\\face2face\\logic\\src\\main\\resources\\log.xml");
    System.exit(0);
}
在上述代码中
options.addOption("c", "cfg", true, "config Absolute Path");第三个参数为true表示需要额外参数:
如定义:String[] arg = {"-t","-c","hello"};//这里参数c在下面定义为需要额外参数,这里是"hello"public void testOption(String[] args) throws ParseException{
Options options = new Options();
options.addOption("t",false,"display current time");
options.addOption("c",true,"country code");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if (cmd.hasOption( "t" )) {
System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())+" in "+cmd.getOptionValue("c"));//这里调用cmd.getOptionValue("c")会输出hello     
} else{
System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
} }

猜你喜欢

转载自blog.csdn.net/ylf_2278880589/article/details/80811304