Does Java have a class to work with command line arguments?

Asked

Viewed 753 times

13

I need to create a Java desktop app, and with it pass several parameters of the type:

java meuapp.jar -DB c: base.db -user admin -password admin

Is there an easy way to get these parameters? Something like this:

    public static void main(String args[]) {
         TipoMap<String> argum = TipoMap(args);
         usuario = agum.get("user");  
         senha = argum.get("senha");
         ...
    } 
  • 1

    In the main you can pass several arguments, precisely why it takes a string array.

  • 1

    Here is some material that can help (as long as no one gives an appropriate answer): http://stackoverflow.com/questions/367706/how-to-parse-command-line-arguments-in-java

  • 1

    Ex.: public static void main(String args[]) in that args[] is where you will handle the expected arguments(in your case, user and password) within your code. That’s what you want to do?

  • 1

    This I know, I want an easy and readable way to do this.

3 answers

13


One of the most well-known libraries that does this is Commons.CLI. With it it is possible to treat arguments as the AP wishes. With it it establishes what options are possible, the format and then processes what came through the command line, determining what to execute. It is very intuitive and has good abstraction to stick to the final result and not to the mechanism of reading the arguments.

Example of documentation:

// create the command line parser
CommandLineParser parser = new DefaultParser();

// create the Options
Options options = new Options();
options.addOption( "a", "all", false, "do not hide entries starting with ." );
options.addOption( "A", "almost-all", false, "do not list implied . and .." );
options.addOption( "b", "escape", false, "print octal escapes for nongraphic "
                                         + "characters" );
options.addOption( OptionBuilder.withLongOpt( "block-size" )
                                .withDescription( "use SIZE-byte blocks" )
                                .hasArg()
                                .withArgName("SIZE")
                                .create() );
options.addOption( "B", "ignore-backups", false, "do not list implied entried "
                                                 + "ending with ~");
options.addOption( "c", false, "with -lt: sort by, and show, ctime (time of last " 
                               + "modification of file status information) with "
                               + "-l:show ctime and sort by name otherwise: sort "
                               + "by ctime" );
options.addOption( "C", false, "list entries by columns" );

String[] args = new String[]{ "--block-size=10" };

try {
    // parse the command line arguments
    CommandLine line = parser.parse( options, args );

    // validate that block-size has been set
    if( line.hasOption( "block-size" ) ) {
        // print the value of block-size
        System.out.println( line.getOptionValue( "block-size" ) );
    }
}
catch( ParseException exp ) {
    System.out.println( "Unexpected exception:" + exp.getMessage() );
}

I put in the Github for future reference.

5

Yes, there is.

You know that class main(String[] args) what is the entry point of your application? It is in this variable args that the parameters entered when calling the application are stored.

When you do

java meuapp.jar param1 param2 param3

all these parameters will be in the array args

I think it’s interesting that you read that one reply


See an example of how to use them:

public class Program {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
} 
  • that I already knew. what I want is not to have to go through the array and have to guess which order of the parameters

  • It would be interesting to have put this information in the question.

  • Excuse me, could you help me explain my need? my question has even been answered, but there may be others with the same doubt.

  • But if you want you can edit the question.

  • @Hagahood would just find it interesting to comment that you know how to use the method parameters main. Anyway I will leave my reply here for collaboration purposes with other people who have this doubt, even if it does not answer your.

4

If you use the framework Spring to do dependency injection and manage your Beans, you can decouple your code from searching command lines and simply inject read values from the environment.

Example:

@Component
public class MeuComponente {

    @Value("${usuario}")
    private String usuario;

}

See the documentation and you will see that the injected values are read from several sources, the first being the command line arguments, but also including Java system properties (system properties), environment variables and Spring configuration file.

This approach is flexible and makes it easy to test components individually, as well as allowing multiple system configuration mechanisms. For example, the user can set the database as an environment variable, while the password is passed via command line argument and other default settings are set in the file application.properties that goes along with the system.

And if at any time you need to access the arguments more directly, just inject ApplicationArguments. Example:

@Component
public class MeuComponente {

    @Autowired
    public MeuComponente(ApplicationArguments args) {
        List<String> dbs = arg.getOptionValues("DB");
        if (!dbs.isEmpty()) {
            carregaDB(dbs.get(0));
        }
    }

}

Of course, if you want to accept arguments more elaborately as in native programs of the operating system, it is better to use another library (as cited in the reply of @Maniero), although my general recommendation would simply be not to use Java.

  • Thank you! but well that I wanted not to use java desktop, but since I have to do integration with a system that the integration library is only provided in java, I don’t have much alternative

  • 1

    @Hagahood I see. Good luck. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.