<dependencies>
<dependency>
<groupId>gnu.getopt</groupId>
<artifactId>java-getopt</artifactId>
<version>1.0.14</version>
</dependency>
</dependencies>
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
public class CommandLineParser {
public static void main(String[] args) {
LongOpt[] longOpts = new LongOpt[3];
longOpts[0] = new LongOpt("file", LongOpt.REQUIRED_ARGUMENT, null, 'f');
longOpts[1] = new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v');
Getopt g = new Getopt("CommandLineParser", args, "f:v", longOpts);
int c;
String file = "";
boolean verbose = false;
while ((c = g.getopt()) != -1) {
switch (c) {
case 'f':
file = g.getOptarg();
break;
case 'v':
verbose = true;
break;
default:
System.out.println("Invalid option: " + (char) c);
break;
}
}
System.out.println("File: " + file);
System.out.println("Verbose: " + verbose);
System.out.println("Remaining arguments: ");
for (int i = g.getOptind(); i < args.length; i++) {
System.out.println(args[i]);
}
}
}
java CommandLineParser -f input.txt -v param1 param2
File: input.txt
Verbose: true
Remaining arguments:
param1
param2