<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>1.78</version>
</dependency>
import com.beust.jcommander.Parameter;
public class CommandLineArgs {
@Parameter(names = { "-h", "--help" }, help = true, description = "Print help message")
private boolean help;
@Parameter(names = { "-f", "--file" }, required = true, description = "File path")
private String filePath;
public String getFilePath() {
return filePath;
}
public boolean isHelp() {
return help;
}
}
import com.beust.jcommander.JCommander;
public class Main {
public static void main(String[] args) {
CommandLineArgs commandLineArgs = new CommandLineArgs();
JCommander.newBuilder()
.addObject(commandLineArgs)
.build()
.parse(args);
if (commandLineArgs.isHelp()) {
System.out.println("Usage: java -jar myapp.jar [options]");
System.out.println("Options:");
JCommander.newBuilder()
.addObject(commandLineArgs)
.build()
.usage();
return;
}
String filePath = commandLineArgs.getFilePath();
System.out.println("File path: " + filePath);
// ...
}
}
java -jar myapp.jar -f /path/to/file.txt