简体   繁体   English

如何获取命令行Java应用程序的多个源文件

[英]How to get multiple source files for a command line java application

I am writing a command line java application and planning to use a library to parse the command line options. 我正在编写一个命令行Java应用程序,并计划使用一个库来解析命令行选项。 and I want to take multiple file names as input. 我想将多个文件名作为输入。

For now I have chosen apache commons-cli (1.2). 现在,我选择了apache commons-cli(1.2)。 My main method is as follows 我的主要方法如下

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("s", "source", true, "file(s) as input");

    CommandLineParser parser = new GnuParser();
    CommandLine input = null;
    try{
        input = parser.parse(options, args);
    }catch (ParseException e){
        new HelpFormatter().printHelp("Usage: ", options);
        System.exit(1);
    }

    String [] files = null;
    if(input.hasOption("s")){
        files = input.getOptionValues("s");         
    }
 }

Now when I execute the program with arguments "-s /home/keshava/file1 /home/keshava/file2" I get only one file in files array. 现在,当我使用参数"-s /home/keshava/file1 /home/keshava/file2"执行程序时,在文件数组中只有一个文件。

I know I can get multiple files by "-s /home/keshava/file1 -s /home/keshava/file2" But I dont want to do that. 我知道我可以通过"-s /home/keshava/file1 -s /home/keshava/file2"获取多个文件,但我不想这样做。

Is there a way to specify a value separator in any way? 有没有办法以任何方式指定值分隔符? Any other library suggestion is also ok. 任何其他图书馆的建议也可以。

Thanks, Keshava 谢谢,Keshava

In case anyone is still looking for an answer, you can get multiple values in the array by specifying the maximum number of values for a given option supports using the setArgs() method. 如果有人仍在寻找答案,则可以使用setArgs()方法通过指定给定选项支持的最大值数目来在数组中获取多个值。

Options options = new Options();
Option option = new Option("s", "source", true, "file(s) as input");
// Let option s take up to 5 arguments
option.setArgs(5);
options.addOption(option);

The setArgs() method also accepts Option.UNLIMITED_VALUES when the maximum number of values does not have a fixed limit. 当最大数量的值没有固定限制时, setArgs()方法也接受Option.UNLIMITED_VALUES

If using OptionBuilder , the method hasArgs() can be applied to the builder, optionally with the limit. 如果使用OptionBuilder ,则方法hasArgs()可以应用于构建器(可选)。 Without no limit specified it will use Option.UNLIMITED_VALUES . 没有指定限制,它将使用Option.UNLIMITED_VALUES

// Unlimited
options.addOption(OptionBuilder.withArgName("file(s)").hasArgs().withLongOpt("files").create("f"));

// Limit to 5
options.addOption(OptionBuilder.withArgName("file(s)").hasArgs(5).withLongOpt("files").create("f"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM