Java Command Line Arguments

How do I parse command line arguments in Java?

Check these out:

  • http://commons.apache.org/cli/
  • http://www.martiansoftware.com/jsap/

Or roll your own:

  • http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

For instance, this is how you use commons-cli to parse 2 string arguments:

import org.apache.commons.cli.*;

public class Main {

public static void main(String[] args) throws Exception {

Options options = new Options();

Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);

Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);

CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;//not a good practice, it serves it purpose

try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);

System.exit(1);
}

String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");

System.out.println(inputFilePath);
System.out.println(outputFilePath);

}

}

usage from command line:

$> java -jar target/my-utility.jar -i asd                                                                                       
Missing required option: o

usage: utility-name
-i,--input <arg> input file path
-o,--output <arg> output file

When should we use command line arguments?

That is just an another way of doing things. Sometimes command line arguments are useful for quickly checking how your program responds with different inputs. I guess you just started your programming journey and that is why you are asking question like this.

And let me tell you there is a difference between argument and input. Scanner class helps you to take input from the console whereas command line arguments are passed as an argument to your main function.

Here are some advantages of using command line arguments.

  1. You can pass any number of arguments and you do not need to define variables for them.
  2. The next benefit is you can pass any data type with command line and then you can code your functions accordingly.

And the final answer for you, don't think about why this when we already have this. It is programming and you should learn as much as you can. You will find 1000s ways of doing the same thing. So enjoy learning.

Parsing command line args[], with flags and without using a third party lib

This is how I solved the problem. It assumes there are class member variables set with default values to overide.

private String ipAddress = "localhost";

private Integer port = 14001;

     /**
* Method to get the ip and port number from the command line args.
* It caters for any order of flag entry.It tries to override the
* defaults set as a class variables, so if it can't, it uses those.
*
* @param args The args passed in by the user.
*/
private void getPortAndIp(String[] args) {
System.out.println("Getting inputs ");
if ((args[0].equals("-ccp")) && (args.length == 2)) {
this.port = Integer.parseInt(args[1]);
} else if ((args[0].equals("-cca")) && (args.length == 2)) {
this.ipAddress = args[1];
} else if ((args[0].equals("-ccp")) && (args[2].equals("-cca"))
&& (args.length == 4)) {
this.port = Integer.parseInt(args[1]);
this.ipAddress = args[3];
} else if ((args[0].equals("-cca")) && (args[2].equals("-ccp"))
&& (args.length == 4)) {
this.port = Integer.parseInt(args[3]);
this.ipAddress = args[1];
} else {
System.out.println("Options:");
System.out.println("-ccp [port number]");
System.out.println("-cca [ip address]");
System.out.println("Could not determine port from command line " +
"arguments, using defaults: ");
}
System.out.println("on " + this.ipAddress + ":" + this.port);
}

command line argument with variable name in java in specific format

The below code will work if key and value pairs are only space-separated.

public static void main(String[] args) {

Map<String, String> argMap = new LinkedHashMap<>();

for(int ind=0; ind<args.length; ind+=2) {
argMap.put(args[ind], args[ind+1]);
}

for(Map.Entry<String, String> entrySet: argMap.entrySet()) {
String property = entrySet.getKey().substring(2);
String value = entrySet.getValue();
System.out.println("key = " + property + ", value = " + value);
}

}

Java command line arguments in --key=value format

Try the -D option, allows to set key=value pair:

run command; note there are no space between -Dkey

  • java -Dday=Friday -Dmonth=Jan MainClass

In your code:

String day = System.getProperty("day");
String month = System.getProperty("month");

Check if command line arguments are in a correct form

I hope it give you some idea:

 public static void main(String[] args) {
args = args[0].split(";");
if (args.length != 4) {
throw new IllegalArgumentException("Program starts with parameters like this: (String, String, int, int)");
}

try {
int firstInt = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, int, int)");
}

try {
int secondInt = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Program starts with parameters like this: (OK, OK, OK, int)");
}
}

How to pass command-line arguments to IntelliJ itself, to alter behavior of IDE (not my own app within IDE)?

How do I know the version of the JVM being used by IntelliJ?

You can find that in the 'about' dialog:

about dialog

Can I point IntelliJ towards another JVM for its own operations, for a later version of 17 (understanding that I am operating IntelliJ in an untested and unsupported environment)?

Technically you can, but it might cause problems in your IDE I think? There's a warning in their documentation, see Change the boot Java runtime of the IDE to switch to a custom JDK.

How do I pass a command-line argument to that JVM when IntelliJ is launching?

Once your IDE is running, go to Help > Edit Custom VM options, see their Advanced configuration page.



Related Topics



Leave a reply



Submit