Processing Command Line Arguments in Java
Join the DZone community and get the full member experience.
Join For FreeRather than parsing command line arguments yourself, Apache has a nice library to do it for you, called Apache Commons CLI. It has a few different options, for various flavors of parsing, although this example demonstrates the two most common use cases (I think) – a flag, and setting a value.
The nice thing about this is it warns you if you specify incorrect arguments, so you can avoid worrying about that ever again.
import org.apache.commons.cli.*; public class ArtEtl { public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("d", false, "Delete records"); // does not have a value options.addOption("c", true, "CSV Repository"); // has a value CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse( options, args); if (cmd.hasOption("d")) { System.out.println("Clearing index"); server.deleteByQuery("*:*"); } }
Published at DZone with permission of Gary Sieling, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments