This post originated from an RSS feed registered with Java Buzz
by Nick Lothian.
Original Post: Command Line Processing in Java
Feed Title: BadMagicNumber
Feed URL: http://feeds.feedburner.com/Badmagicnumber
Feed Description: Java, Development and Me
I've always found processing command line parameters in Java something of
a hassle. It's not hard, but it can be error prone and
having to write the same code over and over is annoying.
Here's a class I wrote that I find useful for this. Usage:
String usage = "java " + YourClass.class.getName() + " -a FirstParam -b
SecondParam";
CmdLineProcessor cmdLine = new CmdLineProcessor(args, usage);
cmdLine.setExpectedArgumentCount(4);
if (cmdLine.process()) {
String firstParam = cmdLine.getArgument("-a");
String secondParam = cmdLine.getArgument("-b");
System.out.println("Parameters were " + firstParam + " and " +
secondParam);
}
// usage message is output if process() did not return true
The class:
public class CmdLineProcessor {
private String[] args;
private int expectedArgumentCount = 0;
private String usageMessage;
public CmdLineProcessor(String[] args, String usage) {
this.args = args;
setUsageMessage(usage);
}
public boolean process() {
if ((args == null)
|| (args.length != expectedArgumentCount)) {
System.err.println(getUsageMessage());
return false;
}
return true;
}
public String getArgument(String param)
throws IllegalArgumentException {
for (int i = 0; i < args.length; i++) {
if (param.equals(args[i] )) {
if (args.length > (i + 1)) {
return args[i+1];
}
}
}
System.err.println(getUsageMessage());
throw new IllegalArgumentException();
}
public int getExpectedArgumentCount() {
return expectedArgumentCount;
}
public String getUsageMessage() {
return usageMessage;
}
public void setExpectedArgumentCount(int i) {
expectedArgumentCount = i;
}
public void setUsageMessage(String string) {
usageMessage = string;
}
}