Created
November 8, 2018 09:20
-
-
Save pcdv/f66e7a60f1c405aec1098f7096a780d9 to your computer and use it in GitHub Desktop.
Parse command line in Java 8 without dependencies
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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