Skip to content

Instantly share code, notes, and snippets.

@pcdv
Created November 8, 2018 09:20
Show Gist options
  • Save pcdv/f66e7a60f1c405aec1098f7096a780d9 to your computer and use it in GitHub Desktop.
Save pcdv/f66e7a60f1c405aec1098f7096a780d9 to your computer and use it in GitHub Desktop.
Parse command line in Java 8 without dependencies
public class Args {
private static final String USAGE //
= String.join("\n",
"",
"tool [options] files...",
"",
"",
"Options:",
" -d PORT : filter on given port",
" -h : prints this help",
"");
final List<String> args = new ArrayList<>();
public int dstPort;
public static class Usage extends RuntimeException {
Usage() {
super(USAGE);
}
Usage(String msg) {
super(msg + "\n" + USAGE);
}
}
Args(String[] argv) {
try {
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.startsWith("-")) {
switch (arg) {
case "-h":
throw new Usage();
case "-d":
dstPort = Integer.parseInt(argv[++i]);
break;
default:
throw new Usage("Unknown option: " + arg);
}
}
else {
args.add(arg);
}
}
}
catch (Usage e) {
throw e;
}
catch (Exception e) {
throw new Usage(e.toString());
}
if (args.isEmpty())
throw new Usage();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment