Class to parse command line arguments.

Hi,
Is there a Class to parse the Command line arguments of a program?
Perhaps something like Getopt in perl.
Thanks,
Anupam.

I'm not sure if this is what you're asking, but it does it for you already. The args[] array in the main method holds the command line arguments parsed with space delimiters. So if on the command line you put:
java MyClass these are arguments
The args array would contain:
args[0] = "these"
args[1] = "are"
args[2] = "arguments"

Similar Messages

  • Parsing command line arguments

    hi ,
    I need to know how to get the output from the command line into my java application. Can anyone help with this coding .
    thanks
    gracy

    Let's keep it all together here:
    http://forum.java.sun.com/thread.jspa?threadID=712895

  • Setting Command Line Arguments for my Class

    HI,
    How do I set the command line arguments for my debug class. For example , I would like my user to type :
    java Debug -LEVEL1
    What should I do to implement this behaviour.
    Thanks in advance...

         public static void main (String[] args){
              if(args.length > 0){
                   int j = 0;
                   BMsearch search = new BMsearch();
                   try{
                        while (j < args.length){
                             if(args[j].equalsIgnoreCase(ONE_PATERN)){
                                  search.addPaternForSearch(args[j+1]);
                                  j = j+2;
                             else if (args[j].equalsIgnoreCase(PATERNLIST)){
                                  j++;
                                  while( ! (args[j].startsWith("-")) ){
                                       search.addPaternForSearch(args[j]);
                                       j++;
                                  }//end while
                             else if (args[j].equalsIgnoreCase(PATERNFILE)){
                                  j++;
                                  search.readPaternFile(args[j]);
                                  j++;
                             else if(args[j].equalsIgnoreCase(MATCH_H)){
                                  search.heuristic = MATCH_HEURISTIC;
                                  j++;
                             else if(args[j].equalsIgnoreCase(MATCH_H2)){
                                  search.heuristic = MATCH_HEURISTIC_TWO;
                                  j++;
                             else if(args[j].equalsIgnoreCase(OCC_H)){
                                  search.heuristic = OCC_HEURISTIC;
                                  j++;
                             else if(args[j].equalsIgnoreCase(COMB_H)){
                                  search.heuristic = COMBINED_HEURISTIC;
                                  j++;
                             else if(args[j].equalsIgnoreCase(JAVA_S)){
                                  search.heuristic = JAVA_NATIVE;
                                  j++;
                             else if(args[j].equalsIgnoreCase(TEXTFILE)){
                                  j++;
                                  search.readFileIn(args[j]);
                                  j++;
                             else if(args[j].equalsIgnoreCase(TEXTURL)){
                                  j++;
                                  search.readURLFileIn(args[j]);
                                  j++;
                             else if(args[j].equalsIgnoreCase(STOPatFIRST)){
                                  search.searchall = false;
                                  j++;
                             else if(args[j].equalsIgnoreCase(STOPatLAST)){
                                  search.searchall = true;
                                  j++;
                             else if(args[j].equalsIgnoreCase(VERBOSE)){
                                  search.verbose = true;
                                  j++;
                             else if(args[j].equalsIgnoreCase("-h") || args[j].equalsIgnoreCase("-help")){
                                  printHelp();
                                  Start = false;
                                  break;
                             else{
                                  System.out.println(" Error while parsing Parameter. ");
                                  System.out.println(" type java BMsearch -help for all Options");
                                  Start = false;
                                  break;
                        }// end outer while
                   catch(Exception e){
                        System.out.println(" Error while parsing Parameter. ");
                        System.out.println(" type java BMsearch -help for all Options");
                        Start = false;
                        j = args.length;
                   if(Start){
                        if(search.verbose)System.out.println(" Parameter parsed, beginning with search ...");
                             search.starttimeTotal = System.currentTimeMillis();
                        search.search();
                        search.stoptimeTotal = System.currentTimeMillis();
                        System.out.println(" Whole search took:  " + (search.stoptimeTotal - search.starttimeTotal) + " milliseconds.(Brutto) ");
              else{
                   System.out.println(" Error while parsing Parameter. ");
                   System.out.println(" type java BMsearch -help for all Options");
         }//end MAINThis is takem from one of my command line classe (a Boyer Moore Pattern-Matching application from an exercise). I don't know if this is the best way, but thats what I have done there for passing some arguments, where the order of them isn't pre-given (you can pass the params in the order you want).
    The CAPITAL vars are pre-defined final Strings holding the param-names, e.g.
    public static final String ONE_PATERN = "-p";
    public static final String PATERNLIST = "-plist";
    public static final String PATERNFILE = "-pfile";Another trick sometimes used in Linux/Unix, if you have only false/true combinations, are numbers from pow 2 (2,4,8,16). In C they are used because of the binary representation, but it has some benefits. E.g. a value of 2 (0010) and another true set on 4 (0100) results binary in 6 (0110), so you can mix parameters in only one value, and with a byte - array you could check, if the flag for a given param is set. But this way is a little tricky for the end-user.

  • Need Help with command line arguments for a class method

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its command line arguments which are numbers. For example, if the input was .... 5 2 3....then the output would be 10.
    I have been told to use the Convert to convert a string to a double. I'm ok for writing the class method but I have no idea how to use Convert and why I need it in the method.
    Can anybody help please?

    Hey guys,
    I'm fairly new to programming in java.
    I want to a write a class method that adds up its
    command line arguments which are numbers. For
    example, if the input was .... 5 2 3....then the
    output would be 10.Okay. So you would receive the numbers to add as the String[] argument to a main method. The steps are simple:
    1) declare a variable for the count
    2) for each String in the array:
    2.1) extract the value as a double
    2.2) add this to the count
    3) output the resulting count
    I have been told to use the Convert to convert a
    string to a double.
    I'm ok for writing the class
    method but I have no idea how to use ConvertThere is no class Convert in the Java API.
    and why
    I need it in the method. Do you understand you need to somehow convert each String to a double (step 2.1)? Since Convert is unknown to me, maybe you should just take a look at class Double. It can help you do step 2.1, the rest should be trivial enough.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html
    Give it a go and feel free to post back with a specific problem you are having, accurately described if you please :-)

  • How to run command line argument programe

    Hi guys, I am doing pass command line argument programe in java but I don't know how to run this programe. Path for this programe in my my computer is C:\Users\Desktop\Mainjava\mycode\CommandProgjava*
    {code/}
    public class CommandProg
    public static void main(String[] args)
    System.out.println("d");
    for (int i = 0; i < args.length; i++)
    System.out.println(args);
    {code/}
    Where i need to go and what command i need to give so i can execute this programe(I am using window vista). I only know i have to give
    this command some where CommandProg arg1 arg2 arg3 arg4. Output should be
    Output:
    arg1
    arg2
    arg3
    arg4
    Please help me, Thanks in advance.
    Edited by: JayVirk on Dec 30, 2007 11:33 AM

    Jay,
    Your question isn't very clear, hence Joerg's well meaning but irrelevant advise.
    Do you mean:
    I've written a simple program in java which echos
    it's command-line arguments to back to the console.
    Here's my code:
    package forums;
    public class ArgsEchoer
      public static void main(String[] args) {
        for (String arg : args) {
          System.out.println(arg);
    But can't figure out how to compile and run the program.
    I'm using winblows shista, and it's cr@p.
    Please help me, Thanks in advance.So... where are you at? Have you installed the JDK (java development kit)? Which version? Is your path set? Is your classpath set?
    Start here: http://java.sun.com/developer/onlineTraining/new2java/

  • Sending varargs via command line arguments to main()

    When I put A B C D in the command line arguments textbox in my compiler, the output is as expected: A B C D. However, when I put *new String[]{A, B, C, D}*, the output is *new String[]{A, B, C, D}*, not A B C D as I had expected. My code is below. Any suggestions?
    package varargs;
    public class Varargs {
        static void printArray(Object...args){
            for (Object obj : args)
                System.out.print(obj + " ");
            System.out.println();
        public static void main(String...args) {
            printArray((Object[])args);
    }

    The argument(s) that is/are supplied to your main method will be rendered as literal String constants. It looks like you are attempting to use java code as one of your arguments with the expectation that the program will interpret this code. It won't. Your program will simply display whatever it is given even if what you offer as an argument happens to be a construct of the Java language.

  • Sending Command Line Arguments to Jar Executable

    Hi All
    I wish to send Command Line Arguments to Jar Executable.
    i.e. before I Jar'd my program, I would do the following
    public class CmdLnArgmntExp {
    public static void main(String[] args) {
    System.out.println("d");
    for (int i = 0; i < args.length; i++)
    System.out.println(args);
    Running the program in Console.
    Java CmdLnArgmntExp arg1 arg2 arg3 arg4Output:
    arg1
    arg2
    arg3
    arg4
    How would I do this to a Jar executable, hope that made sense
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    java -jar executable-jar-file-containing-class-CmdLnArgmntExp.jar arg1 arg2 arg3 arg4

  • Connection string not in the command line argument.

    Hi,
    I found myself constantly looking for the debug connection string and to enter it in the "Command line arguments".  I decided to create my Add-On base class from which all my add-ons inherit from.
    In the constructor of the base Add-On class I determine the connection string based on whether the code is in debug more or not.
    Example:
    string connectionString  = string.Empty;
    #if DEBUG
        _connectionString = "0030002C0030002C00530041005000420044005F00440061007400650076002C0050004C006F006D0056004900490056";
    #else
        // Get the log info
        if (Environment.GetCommandLineArgs().Length > 1 )
            _connectionString = Environment.GetCommandLineArgs().GetValue(1).ToString();
    #endif
    I hope this help.
    Edited by: B1Computing on Apr 5, 2011 8:20 PM

    Hi,
    I found myself constantly looking for the debug connection string and to enter it in the "Command line arguments".  I decided to create my Add-On base class from which all my add-ons inherit from.
    In the constructor of the base Add-On class I determine the connection string based on whether the code is in debug more or not.
    Example:
    string connectionString  = string.Empty;
    #if DEBUG
        _connectionString = "0030002C0030002C00530041005000420044005F00440061007400650076002C0050004C006F006D0056004900490056";
    #else
        // Get the log info
        if (Environment.GetCommandLineArgs().Length > 1 )
            _connectionString = Environment.GetCommandLineArgs().GetValue(1).ToString();
    #endif
    I hope this help.
    Edited by: B1Computing on Apr 5, 2011 8:20 PM

  • Problem associated with Command Line arguments

    hi ,
    I am not able to pass a file path as command line argument in java.
    Actually i want to run a java program from the command prompt passing a file path . Something like this i tried to do , but its not working.
    D:\VISHAL\src> java CopyFile C:\Documents and Settings\Administrator\Desktop\link.txt
    where ,
    CopyFile is the name of my class which i am going to run
    C:\Documents and Settings\Administrator\Desktop\link.txt is the argument.
    Can anyone tell me whether a java program accepts an argument like this, if yes please tell me the exact syntax..
    Thanks
    Vishal J
    Message was edited by:
    vishal_vj

    is there any other way of solving this?Y don't U try it out with the logic as mentioned
    below it wud be the case if U r not going with
    java CopyFile "C:\Documents and
    Settings\Administrator\Desktop\link.txt" 1
    String filepath = new String();
    for(int i = 0; i < Arg.length; i++)
    filepath.append(Arg);
    File f = new File(filepath);
    What????  This is a non-solution to a non-problem.  First of all, you would be constructing a filename without spaces, when the real path contains spaces.  Secondly, even if you did insert spaces it would not matter.  What if the String (and it does not have to be a filename) contained tabs rather than spaces.  The real (and really only) solution to the problem is to put quotes around the argument, for the exact reason stated in my last post.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Read in file name + path using command line arguments

    Hi guys,
    I am trying to use command line arguments to read in the name of two files. The code below works as long as the files are on the class path.
    public class cmdLineArguments {
         public static void main(String[] args) {
              String xmlFile1 = args[0];
                    String xmlFile2 = args[1];
              System.out.println ("\nXmlFile1: " + args[0] + "\nXmlFile2: " + args[1]);
    }I would like to be able to read files that are not on the class path as well by entering their full path along with their names.
    In other words, It works if I type:
    C:\Documents and Settings\user\workspace\CmdLineArgs\src>java cmdLineArgs file1.xml file2.xmlbut not if I type:
    C:\Documents and Settings\user\workspace\CmdLineArgs\src>java cmdLineArgs c:\Documents and Settings\user\desktop\file1.xml c:\Documents and Settings\user\desktop\file2.xmlWould anyone please explain how I can edit the code to make it work? I guess I could take them both as a String, modify them manually (add a \ to it etc) but is there an easier way to do it? Even a reference to a tutorial, article etc about this would be very much appreciated.
    Also, any idea why a code would compile and run fine in Eclipse but would create an error from command line?
    Thanks a lot.

    You need to learn about cmd.exe which is used to process the command line. The arguments passed to any program is the command line split at white space so your command line arguments of
    c:\Documents and Settings\user\desktop\file1.xml c:\Documents and Settings\user\desktop\file2.xmlis turned into an array of
    "c:\Documents", "and", "Settings\user\desktop\file1.xml", "c:\Documents", "and", "Settings\user\desktop\file2.xml"In other words instead of 2 arguments you actually have 6.
    To get round this the file names need to be quoted
    java cmdLineArgs "c:\Documents and Settings\user\desktop\file1.xml" "c:\Documents and Settings\user\desktop\file2.xml"

  • Reading character * at command line argument?

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class FindDemo {
    public static void main(String[] args) {
    Matcher m =
    Pattern.compile("[aeiouAEIOU]*(\*)[atcgAGCT]*").matcher(
    "agctaEvening is full of the linnet's wings");
    if (m.find())
    System.out.println(m.group());
    Help?
    (\*) - How can I read the * symbol from command line argument?

    If anyone can advise me, I would be very grateful.
    I have a program that takes arguments from command line:
    one a text file and the other a sequence to search against the file.
    The sequence can contain a * which represents more than one letter of the alphabet. e.g AM*N which should yield Amen, Amoran, american
    import java.io.*;
    public class FindTextInFileNine {
        public static void main(String[] args) {
            if(args.length != 2) {
                System.out.println("Usage: java FindTextInFile [file-name] [search-string]");
            else {
                String file = args[0];
                String search = args[1];
             String parameter = search.replaceAll(" ", "");
                String result = parameter(file, parameter);
                System.out.println(result);
        public static String parameter(String file, String parameter) {
            StringBuffer strb = new StringBuffer();
            parameter = parameter.toLowerCase();
    if (parameter.matches("[actgACTG]*") != false){
                      System.out.print("Correct parameters for sequence entered.");
    if (parameter.matches("[aeiouAEIOU]*") != true){
                      System.out.print("ERROR1: Incorrect parameters for sequence entered.");
            try {
                FileReader fr = new FileReader(file);
                BufferedReader input = new BufferedReader(fr);
                int lineNumber = 0;
                String line;
                     while((line = input.readLine()) != null) {
                         line = line.toLowerCase();
                         lineNumber++;
                      System.out.println(parameter.matches("[aeiouAEIOU]*"));
                         if(line.indexOf(parameter) != -1) {
                             strb.append("Found \""+parameter+"\" at line "+lineNumber+
                                         ", starting-index "+line.indexOf(parameter));
                             strb.append('\n');
                   else {
                   System.out.println("Sequence not found in file. Please check and try again");
                input.close();
            catch(IOException e) {
              System.out.println();
                 System.out.println("ERROR2: File not found. Please check file name, file extension and file location.");
            return strb.toString();
    }Any help appreciated.

  • Pass dynamic Command line arguments

    Hi,
    I tried to pass dynamic command line argument to Web start using the method :
    "javaws URL -D foo -D bar"
    as explained in the "Unofficial JWS/JNLP FAQ" that " You can pass your own system properties to your app using -D switch ....", but I got the following error at the start;
    error occurred while launching/running the application.
    Category: Invalid Argument error
    Too many arguments supplied: {http://...URL/my.jnlp, -Did=123 }
    p.s. I already added the"<property name='' value=''/> in the <resourse>, and modified the main class to get the parameter using System. getProperty();
    Did anyone try to this method before? What's wrong of this?
    Thanks in advance for your help.

    Thanks.
    here below is the jnlp file:
    <jnlp spec="1.0+" href="$$name" codebase="$$codebase">
    <information>
    <title>GUI Application</title>
    <vendor>PS</vendor>
    <description>PS GUI WebStart Version</description>
    <icon href="logo.jpg" />
    <offline-allowed />
    </information>
    <resources>
    <j2se version="1.3" />
    <jar href="lib/gui.jar" />
    <property name="id" value="zbc" />
    <jar href="lib/classes12.zip" />
    <jar href="lib/j2ee.jar" />
    <jar href="lib/jaas.jar" />
    <jar href="lib/jce1_2_1.jar" />
    <jar href="lib/jdom.jar" />
    <jar href="lib/xerces.jar" />
    <jar href="lib/local_policy.jar" />
    <jar href="lib/log4j.jar" />
    <jar href="lib/orion.jar" />
    <jar href="lib/sunjce_provider.jar" />
    <jar href="lib/US_export_policy.jar" />
    </resources>
    <security>
    <all-permissions />
    </security>
    <application-desc main-class="GUIFrame">
    </application-desc>
    and in the main class "GUIFrame", i use System.getProperty("id") t get the parameter, if I hardcode the value of the "id" in this jnlp file and use javaws URL, everything's fine, but not the "javaws URL -Did=value" which will return the error as mentioned.
    Thanks again for your help.

  • Documenting command line arguments

    I'm very new to javadoc, and I'm trying to put together a set of guidelines for our developers to follow. One thing I came accross was command line arguments. If a main function is expecting command line arguments, how would this be documented, should @param be used? I didn't see anything about this in the guidelines sun has posted. Any help is greatly appreciated.

    This is my own personal opinion, so don't treat it as a "fact", but I don't think Javadoc is best suited for specifying command line arguments. You could do the following:
    *  Description of main() here...
    * @param args First parameter = xxx, Second parameter = yyy;
    public static void main(String[] args)
    }In this way you can specify all command-line parameters that are required in order to make the appliction run.
    BUT...
    Javadoc is meant more to be a programmatic guide to how to allow Java classes to interoperate. Java classes (mostly) will not care at all what the command-line parameters to the main invocation are. That is information that is only really needed to be known by the application executor at runtime.
    Therefore, for all my apps, I do the following to comment what types of parameters should be passed to the invocation of the application:
    * My App comments...
    * @param args Run application without any parameters to see list of all necessary command-line parameters.
    public static void main(String[] args)
       if (args.length < 1)
          System.out.println("This application allows the following parameters:");
          System.out.println("   Param#1 = xxx, <description>");
          System.out.println("   Param#2 = yyy, <description>");
          System.exit(0);
    }In this way, you do not clutter up the Javadoc APIs (used for classwise interaction) with command-line parameters, but the command-line parameters are still specified by "documentation" (running the application without any parameters).
    If parameters are optional, instead of mandatory, you could do something similar...
    * Documentation...
    * @param args Run -h as first flag for list of all optional parameters.
    public static void main(String[] args)
       if ((args.length > 0) && (args[0].equals("-h"))
          // Print out all possible parameters.
    }Anyway, this system has held me in good stead for the last couple of years.

  • Writing command line arguments

    Is there a way in java to specify which command line argument belongs to each option, like in Perl?
    Like -name Sally -age 23 -city New York
    Or would one have to write their own parsing function to do that?

    You see a lot of quick and dirty initialization code that looks likeif (args.equals("-name")) {setName(args[i+1]);}Obviously the getopts people had to write one too many program with command line arguments.

  • How to read -Dname=value pair command line arguments

    Hi
    iam running one program called report.java as given below
    compile:
    javac report.java
    run:
    java report -Djava.path=home/arao/jaava1.5/bin
    my problem is how to read name and value pair given in command line argument.
    System.getProperty("java.path");//not working can anybody help how to read name and value
    pair of -D option

    If you put that string after the name of the class you are running, then it's a command line parameter. Your main() method can look at args[0] to see it. However it would be better if you just put it before the name of the class, where it's supposed to go if you want it to be treated as a system property.

Maybe you are looking for

  • IPod Touch can't backup after upgrading to iOS4

    I have an iPod touch 2G 8GB, and since I updated to iOS4 it restarts every time it tries to backup. This means that I can't sync, can't put new music/movies/pictures/podcasts on my ipod. I was able to restore, but since it still has iOS4 it still can

  • LaserJet Pro 100 color MFP M175nw

    I am trying to load the driver for my LaserJet Pro 100 color MFP M175nw on my new laptop. It is very slow and after about 10 minutes times out at 99% and says it is a fatal error. I have restarted the PC several times and always with the same result.

  • Can't recover from recovery partition with OneKey after disastrous Win 8.1 upgrade

    I have a U410 that is only a couple months old. A few days ago I decided to take the plunge and accept the free upgrade to Windows 8.1. Big mistake. SInce the upgrade, I've had a slew of problems ranging from programs not running to hard disk integri

  • Lion and iPhoto 09. Please help!

    I just installed Lion and lost all my pictures in the last two years in iPhoto 09. Please help! I know they are on my hard drive but it doesn't populate in iPhoto.

  • How can create report in Spread sheet (Excel sheet)?

    Hi All. I need to prepare report in excel.How can prepare? please help me. Thanks. Jay