<dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>info.picocli</groupId> <artifactId>picocli</artifactId> <version>4.6.1</version> </dependency> import org.apache.commons.cli.*; public class MyApp { public static void main(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "Display help"); options.addOption("v", "verbose", false, "Enable verbose mode"); options.addOption("f", "file", true, "Input file"); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { printHelp(options); return; } String inputFileName = cmd.getOptionValue("f"); } catch (ParseException e) { System.err.println("Error parsing command line arguments: " + e.getMessage()); } } private static void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("myapp", options); } } import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; @Command(name = "myapp", mixinStandardHelpOptions = true, version = "1.0") public class MyApp implements Runnable { @Option(names = { "-v", "--verbose" }, description = "Enable verbose mode") private boolean verbose; @Option(names = { "-f", "--file" }, description = "Input file", required = true) private String inputFile; @Override public void run() { } public static void main(String[] args) { CommandLine.run(new MyApp(), args); } } CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { printHelp(options); return; } String inputFileName = cmd.getOptionValue("f"); } catch (ParseException e) { System.err.println("Error parsing command line arguments: " + e.getMessage()); } CommandLine.run(new MyApp(), args); javac -cp commons-cli-1.4.jar MyApp.java java -cp commons-cli-1.4.jar:. MyApp -h javac -cp picocli-4.6.1.jar MyApp.java java -cp picocli-4.6.1.jar:. MyApp -h


上一篇:
下一篇:
切换中文