6
Nov
2011
Java: Command line argument processing
By Eric Downing. Filed in Java, Scripting, Shell, Utilities |In each language that I have learned I have found it useful to know how to process command line arguments and here is a simple framework that I use for Java. I usually wrap the java command line in a bat or shell file to make it easier to run so that the user does not have to worry about classpath or path issues.
The following is the basic code to handle the command line arguments.
class CmdArgs { public static void main(String[] args) { int argsize = args.length; String curarg; if (argsize > 0 ) { } for(int i = 0; i < argsize; i++) { if (args[i].equals("--host")) { i++; host = args[i]; } else if (args[i].equals("--debug")) { debug = 1; } else { System.out.println("Unknown option: " + args[i]); System.exit(1); } } } }
The bat file for Dos/Windows might look like this:
@echo off java -cp c:javabin;somejar.jar com.etechtips.CmdArgs %*
The shell based file might look like:
java -cp /home/ecdown/javabin:somejar.jar com.etechtips.CmdArgs $*