parsing command line options in Java

i want to write an application

java -jar TEST.jar -u username -h host   etc.....

can someone point me to example of parsing this.
learningunixAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
You can then look up the argument by name e.g.
import java.util.*;
import java.io.*;

public class ArgParser {
    public static void main(String[] args) {
	System.out.println(ArgParser.getOpts(args));
    }

    private static Map<String, String> getOpts(String[] args) {
	Map<String, String> result = new HashMap<String, String>(args.length);
	for(int i = 0;i < args.length;i+=2) {	
	    result.put(args[i], args[i+1]); // trim the leading '-' character if you want from args[i]
	}
	return result;
    }
}

Open in new window

0
 
Minh Võ CôngCommented:
0
 
learningunixAuthor Commented:
I don't have

import org.apache.commons.cli.*;

Is ther any way without inastalling new java packages?
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
Minh Võ CôngCommented:
public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}
http://download.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
0
 
learningunixAuthor Commented:
I am looking something similar to waht we have in C++ GetOpt
0
 
CEHJCommented:
If you organise the args well (as you have) then you should be able to use a Map
0
 
learningunixAuthor Commented:
I just downloaded jot-simple.
I'll give it a try and see

so when I create my own jar file do I have to give all class file of jotsimple also ?
0
 
CEHJCommented:
>>
I just downloaded jot-simple.
I'll give it a try and see
>>

I thought you didn't want to install extra software..?
0
 
learningunixAuthor Commented:
I'll try both and see.

Today is my first day of java programming and trying to do too many things at once and probably jumping a lot.
0
 
CEHJCommented:
>>Today is my first day of java programming

In that case keep it simple: use what i posted and you can go for a more reusable and extensible solution later
0
 
learningunixAuthor Commented:
I found one more tool
jargs.gnu which is also good one.
0
 
learningunixAuthor Commented:
Thanks, I am planning to use jargs.gnu as it is fairly simple.

Thanks once again for the direction.
0
 
CEHJCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.