import org.apache.commons.cli.*; public class CommandLineParserExample { public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption("u", "username", true, "Username"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { printHelp(options); } if (cmd.hasOption("u")) { String username = cmd.getOptionValue("u"); System.out.println("Username: " + username); } } private static void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("CLIExample", options, true); } } import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; @Command(name = "CLIExample", description = "A simple CLI example") public class CommandLineParserExample implements Runnable { @Option(names = {"-h", "--help"}, description = "Print help") private boolean help; @Option(names = {"-u", "--username"}, description = "Username") private String username; public static void main(String[] args) { CommandLine.run(new CommandLineParserExample(), args); } @Override public void run() { if (help) { CommandLine.usage(this, System.out); } if (username != null) { System.out.println("Username: " + username); } } } import com.beust.jcommander.*; public class CommandLineParserExample { @Parameter(names = {"-h", "--help"}, help = true, description = "Print help") private boolean help; @Parameter(names = {"-u", "--username"}, description = "Username") private String username; public static void main(String[] args) { CommandLineParserExample example = new CommandLineParserExample(); JCommander commander = JCommander.newBuilder() .addObject(example) .build(); commander.parse(args); if (example.help) { commander.usage(); } if (example.username != null) { System.out.println("Username: " + example.username); } } }


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