commit afd23a62ba8c90f92256d9f178c651f808c42d65 Author: zuaa Date: Sat Jul 13 11:20:54 2024 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..869b9b1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store +.idea/ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..965818c --- /dev/null +++ b/pom.xml @@ -0,0 +1,70 @@ + + 4.0.0 + + com.example + cli-example + 1.0-SNAPSHOT + + + + + commons-cli + commons-cli + 1.4 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + + + cli.HelloWorldCLI + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + jar-with-dependencies + + + + cli.HelloWorldCLI + + + + + + make-assembly + package + + single + + + + + + + diff --git a/src/main/java/cli/HelloWorldCLI.java b/src/main/java/cli/HelloWorldCLI.java new file mode 100644 index 0000000..c6da8ca --- /dev/null +++ b/src/main/java/cli/HelloWorldCLI.java @@ -0,0 +1,33 @@ +package cli; + +import org.apache.commons.cli.*; + +public class HelloWorldCLI { + public static void main(String[] args) { + // 定义命令行选项 + Options options = new Options(); + options.addOption("h", "help", false, "Print this help message"); + options.addOption("g", "greeting", true, "Set the greeting message"); + + // 创建命令行解析器 + CommandLineParser parser = new DefaultParser(); + + try { + // 解析命令行参数 + CommandLine cmd = parser.parse(options, args); + + if (cmd.hasOption("h")) { + // 输出帮助信息 + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("cli.HelloWorldCLI", options); + } else { + // 获取并输出命令行参数 + String greeting = cmd.getOptionValue("g", "Hello"); + System.out.println(greeting + ", World!"); + } + } catch (ParseException e) { + // 解析失败,输出错误信息 + System.err.println("Error parsing command line: " + e.getMessage()); + } + } +}