Friday, 8 April 2011

Using Getopt in java to give command line options in java program

Wouldn't it be nice if we have command line argument processing in Java with options. I mean using flags and all that stuff for my argumens. Example syntax in Student Database Program:-
java myClassName -c Insert -s John -i 7635425 -b CS
-l {Java|C|C++|nothing} -a []
Flags Explanation:-
'c' may have the following options:-Insert, Delete, Update,Search 's' Student name(compulsory)
'i' Student id(compulsory)
'b' Stuent Major(compulsory)
'l' Student Computer Language Proficiency(choice)
'a' Student Achievements(optional)

So this is where Getopt comes handy.
public static void main(String[] args)
{

//string to hold values for the flags -c,-s,-i,-b,-l and -a
String c,s,i,b,l,a;

for(int count=0;args.length;count+)
{
if(!args[count].startsWith("-"))
{
//even numbered arguments should begin with -
System.out.println("improper suntax");
return;
}
//if args[count]==any flag then args[count+1] contains the
//value for that flag
if(args[count].equals("-c")) c=args[++count];
if(args[count].equals("-s")) s=args[++count];
if(args[count].equals("-i")) i=args[++count];
if(args[count].equals("-b")) b=args[++count];
if(args[count].equals("-l")) l=args[++count];
if(args[count].equals("-a")) a=args[++count];
}
//check for compulsory flags
if(c==null | | s==null | | i==null | | b==null | | l==null)
{
System.out.pritnln("Compulsory flags must be given");
return;
}

int id;
try{
id=Interger.parseInt(i);
}catch(NumberFormatException nfe)
{
Sytem.out.println("Id must be numeric");
return;
}
if(c.equalsIgnoreCase("Insert"))
{
.....
}
if(c.equalsIgnoreCase("Delete"))
{
.....
}
//and so on
...
....
}

Thanks

No comments:

Post a Comment