Wednesday, October 27, 2010

Simple Command Line Parser Class

Here is a very simple class that allows to parse command line parameters.

This is how this class can be used:
...
CmdLineParameterReader cmdReader = new CmdLineParameterReader();
connParams.setHost(cmdReader.getParameterValue(argc,"-host"));
...
Hostname is saved in connParams class in this example.

You can pass hostname "myhost.net" as "-host myhost.net" or "-hostmyhost.net". Both cases are acceptable.


The class is defined as follows


package simple;

public class CmdLineParameterReader {

    String parameterMark = "";
    
    public CmdLineParameterReader(){
        
    }
    
    public CmdLineParameterReader(String parameterMarker){
        this.parameterMark=parameterMarker;
    }

    public String getParameterValue(String args[], String parameter) {
        String valOut = null;
        
        for(int i=0; i<args.length; i++){
            if( args[i].startsWith(parameter) ){
                if(args[i].equals(parameter)){
                    if(   (i+1) < args.length 
                       && ! "".equals(parameterMark)        
                       && ! args[i+1].startsWith(parameterMark)
                       ){
                        valOut = args[i+1];                        
                    }
                    else {
                        valOut = "";
                    }
                }
                else {
                    valOut = args[i].substring(parameter.length());
                }
            }
        }        
        return valOut;
    }    
}

No comments:

Post a Comment