发布日期:2018-03-26
Java中如何解析命令行传递过来的参数?+ 查看更多
Java中如何解析命令行传递过来的参数?
+ 查看更多
发布日期:2018-03-10 10:42
分类:JAVA
浏览次数:134
在Java中解析命令行参数的好方法是什么?
回答
读读这些:
http://commons.apache.org/cli/
http://www.martiansoftware.com/jsap/
http://www.martiansoftware.com/jsap/
或者你浏览下这个:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
比如,这是如何使用commons-cli解析2个字符串参数:
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); } }命令行的用法:
$> java -jar target/my-utility.jar -i asd Missing required option: o usage: utility-name -i,--inputinput file path -o,--output output file