如何解析Java中的命令行参数? [英] How to parse command line arguments in Java?
本文介绍了如何解析Java中的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中解析命令行参数的好方法是什么?
解决方案
b
$ b
或自行编辑:
例如,这是您使用 commons-cli
解析2个字符串参数:
import org.apache.commons.cli。*;
public class Main {
public static void main(String [] args)throws Exception {
选项options = new Options ();
选项输入=新选项(i,输入,true,输入文件路径);
input.setRequired(true);
options.addOption(input);
选项output = new Option(o,output,true,output file);
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options,args);
} catch(ParseException e){
System.out.println(e.getMessage());
formatter.printHelp(utility-name,options);
System.exit(1);
return;
}
String inputFilePath = cmd.getOptionValue(input);
String outputFilePath = cmd.getOptionValue(output);
System.out.println(inputFilePath);
System.out.println(outputFilePath);
}
}
行:
$> java -jar target / my-utility.jar -i asd
缺少必需的选项:o
用法:utility-name
-i, - 输入< arg&输入文件路径
-o, - output< arg>输出文件
What is a good way of parsing command line arguments in Java?
解决方案
Check these out:
Or roll your own:
For instance, this is how you use commons-cli
to parse 2 string arguments:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
return;
}
String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");
System.out.println(inputFilePath);
System.out.println(outputFilePath);
}
}
usage from command line:
$> java -jar target/my-utility.jar -i asd
Missing required option: o
usage: utility-name
-i,--input <arg> input file path
-o,--output <arg> output file
这篇关于如何解析Java中的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文