Java Libraries for command line tools


I needed a simple command line argument parser for a CLI tool which I wanted to create in Java.

Below is the reference I used –

https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java

I ended up using commons cli library since it was lightweight and my use was very basic.

I used the below code provided in the stackoverflow as sample for my parsing use case.

or instance, this is how you use commons-cli to parse 2 string arguments:

import org.apache.commons.cli.*;

public class Main {


public static void main(String[] args) throws Exception {

Options options = new Options();

Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);

Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);

CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;//not a good practice, it serves it purpose

try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);

System.exit(1);
}

String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");

System.out.println(inputFilePath);
System.out.println(outputFilePath);

}

}

Leave a comment