Created
January 14, 2026 07:42
-
-
Save onjin/21cb5334c05163c2a9d0d2f7d722cf89 to your computer and use it in GitHub Desktop.
Example java as script
This file contains hidden or 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
| import java.nio.file.Path; | |
| import java.nio.file.Paths; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| record Options( | |
| boolean verbose, | |
| List<String> inputs | |
| ) {} | |
| public static void main(String[] args) { | |
| Options opts = parseArgs(args); | |
| if (opts.verbose()) { | |
| System.out.println("Verbose mode on"); | |
| System.out.println("Inputs : " + opts.inputs()); | |
| } | |
| // do your work here... | |
| System.out.println("Scripted"); | |
| } | |
| private static Options parseArgs(String[] args) { | |
| boolean verbose = false; | |
| List<String> inputs = new ArrayList<>(); | |
| for (int i = 0; i < args.length; i++) { | |
| String a = args[i]; | |
| switch (a) { | |
| case "-h", "--help" -> { | |
| printUsage(); | |
| System.exit(0); | |
| } | |
| case "-v", "--verbose" -> verbose = true; | |
| default -> { | |
| if (a.startsWith("-")) { | |
| System.err.println("Unknown option: " + a); | |
| printUsage(); | |
| System.exit(1); | |
| } else { | |
| // positional argument | |
| inputs.add(a); | |
| } | |
| } | |
| } | |
| } | |
| return new Options(verbose, List.copyOf(inputs)); | |
| } | |
| private static String requireValue(String[] args, int i, String opt) { | |
| if (i >= args.length) { | |
| System.err.println("Option " + opt + " requires a value"); | |
| printUsage(); | |
| System.exit(1); | |
| } | |
| return args[i]; | |
| } | |
| private static void printUsage() { | |
| String usage = """ | |
| Usage: example [OPTIONS] [INPUTS...] | |
| Options: | |
| -h, --help Show this help message and exit | |
| -v, --verbose Enable verbose output | |
| Examples: | |
| ./example input1.txt input2.txt | |
| ./example -v input1.txt | |
| """; | |
| System.out.print(usage); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment