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

时间:2014-07-24 10:59:34

标签: java apache-commons

我正在编写一个命令行java应用程序并计划使用库来解析命令行选项。 我想把多个文件名作为输入。

现在我选择了apache commons-cli(1.2)。 我的主要方法如下

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");         
    }
 }

现在我用参数"-s /home/keshava/file1 /home/keshava/file2"执行程序 我在文件数组中只得到一个文件。

我知道我可以通过"-s /home/keshava/file1 -s /home/keshava/file2"获取多个文件 但我不想这样做。

有没有办法以任何方式指定值分隔符? 任何其他图书馆建议也可以。

谢谢, Keshava

2 个答案:

答案 0 :(得分:0)

如果有人仍在寻找答案,您可以通过使用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);

当最大值数没有固定限制时,setArgs()方法也接受Option.UNLIMITED_VALUES

答案 1 :(得分:0)

如果使用OptionBuilder,方法hasArgs()可以应用于构建器,可选择使用限制。如果没有指定限制,它将使用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"));
相关问题