使用Apache commons-cli包进行命令行参数解析的示例代码

 更新时间:2018年05月22日 14:14:40   作者:xuejianbest  
Apache的commons-cli包是专门用于解析命令行参数格式的包。这篇文章给大家介绍使用Apache commons-cli包进行命令行参数解析的示例代码,感兴趣的朋友跟随脚本之家小编一起学习吧

Apache的commons-cli包是专门用于解析命令行参数格式的包。

 依赖:

<dependency>
  <groupId>commons-cli</groupId>
  <artifactId>commons-cli</artifactId>
  <version>1.3.1</version>
</dependency>

使用此包需要:

1.先定义有哪些参数需要解析、哪些参数有额外的选项、每个参数的描述等等,对应Options类
 比如说一个命令行参数是 -hfbv,我们定义的Options的目的是,说明哪些参数是真正需要解析的参数:如我们定义了Option:h、f、b,那么在解析的时候解析器就可以知道怎么去用定义的Option匹配命令行从而获取每个参数。而且可以定义哪些参数需要选项,如tar -f ,f参数就需要文件名选项,通过定义解析器才可以把f后面的内容解析为f指定的文件名。

2.根据定义的需要解析的参数对命令行参数进行解析,对应CommandLineParser类
 根据定义的Options对象去解析传入的String[] argus参数,从而匹配出每个参数,然后我们就可以单独获取每个参数。

3.解析完成返回CommandLine对象,由这个对象可获取此次命令行参数的信息。
 可以从这个对象中知道哪些参数输入了,哪些参数没有输入,哪些参数的额外选项的内容等等。然后我们就能自己写代码根据不同参数执行不同逻辑了。

示例代码:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;​
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
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 com.lwt.util.DirUtil;​
public class CommandLineUtil {
  private String[] args;
  private Options opts = new Options();
  private File keyFile;
  private boolean encrypt;
  private boolean create;
  private boolean enName;
  private File[] files;
  private File[] dirs;
  public File getKeyFile() {
    return keyFile;
  }
  public boolean isEncrypt() {
    return encrypt;
  }
  public boolean isEnName() {
    return enName;
  }
  public boolean isCreate() {
    return create;
  }
  public File[] getFiles() {
    return files;
  }
  public File[] getDirs() {
    return dirs;
  }
​
  public CommandLineUtil(String[] args) {
    this.args = args;
    definedOptions();
    parseOptions();
    duplicate_removal();
  }
  // 定义命令行参数
  private void definedOptions(){
    Option opt_h = new Option("h", "Show this page.");
    Option opt_e = new Option("e", "encrypt", false, "Encrypt file.");
    Option opt_d = new Option("d", "decrypt", false, "Decrypt file.");
    Option opt_c = new Option("c", "create", false, "Create new key file.");
    Option opt_n = new Option("n", "name", false, "Encrypt file name.");
    Option opt_k = Option.builder("k").hasArg().argName("keyFile")
        .desc("Specify the key file").build();
    Option opt_f = Option.builder("f").hasArgs().argName("file1,file2...")
        .valueSeparator(',')
        .desc("A files list with ',' separate to handle").build();
    Option opt_r = Option
        .builder("r")
        .hasArgs()
        .argName("dir1,dir1...")
        .valueSeparator(',')
        .desc("A directories list with ',' separate to handle its child files")
        .build();
    Option opt_R = Option
        .builder("R")
        .hasArgs()
        .argName("dir1,dir1...")
        .valueSeparator(',')
        .desc("A directories list with ',' separate to recurse handle child files")
        .build();
    opts.addOption(opt_n);
    opts.addOption(opt_c);
    opts.addOption(opt_k);
    opts.addOption(opt_h);
    opts.addOption(opt_e);
    opts.addOption(opt_d);
    opts.addOption(opt_f);
    opts.addOption(opt_r);
    opts.addOption(opt_R);
  }
  // 解析处理命令行参数
  private void parseOptions(){
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    // 解析命令行参数
    try {
      line = parser.parse(opts, args);
    } catch (ParseException e) {
      System.err.println(e.getMessage());
      System.exit(1);
    }
​
    // 若指定h则显示帮助
    if (args == null || args.length == 0 || line.hasOption("h")) {
      HelpFormatter help = new HelpFormatter();
      help.printHelp("encrypt", opts);
    }
​
    // 选择加密或解密操作,默认是加密文件
    if (line.hasOption("d")) {
      if (line.hasOption("e")) {
        System.err
            .println("The -e and -d option can't specify at the same time.");
        System.exit(1);
      }
      encrypt = false;
    } else {
      encrypt = true;
      if(line.hasOption("n")){
        enName = true;
      }
    }
    if (line.hasOption("k")) {
      String k = line.getOptionValue("k");
      File file = new File(k);
      if (line.hasOption("c")) {
        keyFile = file;
        create = true;
      }else {
        if(file.isFile()){
          keyFile = file;
        } else{
          System.err.println(file + " is not a available key file");
          System.exit(1);
        }
      }
    }
​
    ArrayList<File> files = new ArrayList<File>();
    ArrayList<File> dirs = new ArrayList<File>();
    if (line.hasOption("f")) {
      String[] fs = line.getOptionValues("f");
      for(String f : fs){
        File file = new File(f);
        if(file.isFile()){
          files.add(file);
        }else{
          System.err.println(file + " is not a file");
          System.exit(1);
        }
      }
    }
​
    if (line.hasOption("r")) {
      String[] rs = line.getOptionValues("r");
      for(String r : rs){
        File dir = new File(r);
        if(dir.isDirectory()){
          dirs.add(dir);
          DirUtil dirUtil = new DirUtil(dir);
          files.addAll(Arrays.asList(dirUtil.getFiles()));
          dirs.addAll(Arrays.asList(dirUtil.getDirs()));
        }else{
          System.err.println(dir + " is not a directory");
          System.exit(1);
        }
      }
    }
​
    if (line.hasOption("R")) {
      String[] Rs = line.getOptionValues("R");
      for(String R : Rs){
        File dir = new File(R);
        if(dir.isDirectory()){
          dirs.add(dir);
          DirUtil dirUtil = new DirUtil(dir);
          files.addAll(Arrays.asList(dirUtil.getAllFiles()));
          dirs.addAll(Arrays.asList(dirUtil.getAllDirs()));
        }else{
          System.err.println(dir + " is not a directory");
          System.exit(1);
        }
      }
    }
    this.files = files.toArray(new File[0]);
    this.dirs = dirs.toArray(new File[0]);
  }
  public void duplicate_removal (){
    HashSet<File> fileSet = new HashSet<File>();
    for(File file : files){
      try {
        fileSet.add(file.getCanonicalFile());
      } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
      }
    }
    files = fileSet.toArray(new File[0]);
    fileSet = new HashSet<File>();
    for(File dir : dirs){
      try {
        fileSet.add(dir.getCanonicalFile());
      } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
      }
    }
    dirs = fileSet.toArray(new File[0]);
  }
}

总结

以上所述是小编给大家介绍的使用Apache commons-cli包进行命令行参数解析的示例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • 初识centos7与centos6的区别整理(内核、命令等)

    初识centos7与centos6的区别整理(内核、命令等)

    这篇文章主要介绍了初识centos7与centos6的区别整理,需要的朋友可以参考下
    2017-08-08
  • CentOS 8 正式发布 基于Red Hat Enterprise Linux 8

    CentOS 8 正式发布 基于Red Hat Enterprise Linux 8

    紧随CentOS Linux 7.7发行版之后,CentOS Linux 8现已正式发布,新版本基于Red Hat Enterprise Linux 8.0源,这意味着它具有混合云时代的所有强大的新特性和增强功能
    2019-09-09
  • linux下图形界面卡死不能操作的问题及解决

    linux下图形界面卡死不能操作的问题及解决

    这篇文章主要介绍了linux下图形界面卡死不能操作的问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • 详解ubuntu14.04如何设置静态IP的方法

    详解ubuntu14.04如何设置静态IP的方法

    本篇文章主要介绍了ubuntu14.04如何设置静态IP的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • 关于AIX挂载NFS写入效率低效的解决方法

    关于AIX挂载NFS写入效率低效的解决方法

    这篇文章主要给大家介绍了关于AIX挂载NFS写入效率低效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • 服务器端如何开启GZIP压缩功能(Apache、IIS、Nginx)

    服务器端如何开启GZIP压缩功能(Apache、IIS、Nginx)

    在负载均衡中有一个必须要做的事情就是给服务器开启GZIP压缩功能,本文主要介绍了服务器端如何开启GZIP压缩功能,具有一定的参考价值,感兴趣的可以了解下
    2022-04-04
  • Linux中chmod权限设置方式

    Linux中chmod权限设置方式

    本文介绍了Linux系统中文件和目录权限的设置方法,包括chmod、chown和chgrp命令的使用,以及权限模式和符号模式的详细说明,通过这些命令,用户可以灵活地控制文件和目录的访问权限
    2025-01-01
  • ubuntu系统中/etc/rc.local和/etc/init.d/rc.local的区别详解

    ubuntu系统中/etc/rc.local和/etc/init.d/rc.local的区别详解

    这篇文章主要给大家介绍了关于在ubuntu系统下/etc/rc.local和/etc/init.d/rc.local区别的相关资料,文中通过示例代码介绍的非常详细,对需要的朋友们具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-08-08
  • Linux服务器从头配置全过程

    Linux服务器从头配置全过程

    这篇文章主要介绍了Linux服务器从头配置全过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-03-03
  • Linux ssh服务器配置代码实例

    Linux ssh服务器配置代码实例

    这篇文章主要介绍了Linux ssh服务器配置代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09

最新评论