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
How to parse some of the command line arguments to a single option in Java
args4j can't do that, I think. I wouldn't use args4j, it's.. outdated.
Try jcommander. It's the exact same idea, but unlike with args4j, you can stick the jcommander take on @Option
on a List<T>
. See section 2.2 of the docs (click the link, go to 2.2. :P)
HOWEVER: Note that if I take your question literally, what you're asking is highly inadvisable!
In posix-style command line arguments, your string is parsed as:
-i firstFile
- okay, firstFile is the argument for the -i option.secondFile
- okay, this is completely unrelated to the -i, this is a file argument.thirdFile
- same deal.-o outFile
- outFile is the argvalue for the -o switch.
What you presumably want, and how jcommander works, is that you'd have to write:
java -jar myprog.jar -i firstFile -i secondFile -i thirdFile -o outFile
if you really want -i firstFile secondFile thirdFile
to work, that's a bit weird / non-standard, and naturally, when want nonstandard things, standard libraries are unlikely to be capable of delivering for you, so you'd have to write it all by hand. I'd advise you.. change what you want, a little, to fall in line with what people expect, and thus, gain the benefit of using a library to get it for you.
However, going further down this rabbithole of command line design, going with -i in1 -i in2 -i in3
is better, but still non idiomatic and unwieldy. The usual rule is that inputs are fielded via no-switch. The proper way to write your command line would be:
java -jar myprog.jar -o outFile firstFile secondFile thirdFile
This is how zip
, curl
, ffmpeg
, java
(the executable) itself, etc all work.
both args4j and jcommander can do this; args4j via @Arguments List<String> args;
, jcommander via @Parameter
.
Parsing arguments to a Java command line program
You could just do it manually.
NB: might be better to use a HashMap instead of an inner class for the opts.
/** convenient "-flag opt" combination */
private class Option {
String flag, opt;
public Option(String flag, String opt) { this.flag = flag; this.opt = opt; }
}
static public void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<Option> optsList = new ArrayList<Option>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].length < 2)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
if (args[i].charAt(1) == '-') {
if (args[i].length < 3)
throw new IllegalArgumentException("Not a valid argument: "+args[i]);
// --opt
doubleOptsList.add(args[i].substring(2, args[i].length));
} else {
if (args.length-1 == i)
throw new IllegalArgumentException("Expected arg after: "+args[i]);
// -opt
optsList.add(new Option(args[i], args[i+1]));
i++;
}
break;
default:
// arg
argsList.add(args[i]);
break;
}
}
// etc
}
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);
}
Java parsing command line arguments ( args[]) into an int[][] Type
public static void main(String[] args) throws IOException {
List<Integer[][]> arrays = new ArrayList<Integer[][]>();
//Considering the k=0 is the show, sum or divide argument
for(int k=1; k< args.length; k++) {
String[] values = args[k].split(";|,");
int x = args[k].split(";").length;
int y = args[k].split(";")[0].split(",").length;
Integer[][] array = new Integer[x][y];
int counter=0;
for (int i=0; i<x; i++) {
for (int j=0; j<y; j++) {
array[i][j] = Integer.parseInt(values[counter]);
counter++;
}
}
//Arrays contains all the 2d array created
arrays.add(array);
}
//Example to Show the result i.e. arg[0] is show
if(args[0].equalsIgnoreCase("show"))
for (Integer[][] integers : arrays) {
for (int i=0; i<integers.length; i++) {
for (int j=0; j<integers[0].length; j++) {
System.out.print(integers[i][j]+" ");
}
System.out.println();
}
System.out.println("******");
}
}
input
show 1,2;3,4 5,6;7,8
output
1 2
3 4
******
5 6
7 8
input for inpt with varible one 3*3 one 2*3 matrix
show 1,23,45;33,5,1;12,33,6 1,4,6;33,77,99
output
1 23 45
33 5 1
12 33 6
******
1 4 6
33 77 99
******
Parsing a file passed as argument to Java from command line
Just do a switch case on the first argument (-f
/-s
).
File file;
switch(args[0]){
case "-f" :
file = new File(args[1]);
//do stuff with file1
break;
case "-s" :
file = new File(args[1]);
//do stuff with file2
break;
default :
}
Code Structure for Parsing Command line Arguments in Java
I would recommend to you JCommander.
I think it's a really good Argument Parser for Java.
You define all the Argument stuff within annotations and just call JCommander to parse it.
On top of that it also (based on your annotations) can print out the corresponding help page.
You don't have to take care about anything.
I believe you will love it! :)
Take a look at it: http://jcommander.org/
There are a lot of examples and such!
Good Luck! :)
Java code fails to parse command line arguments pass from wrapper script
Is there an LF or CR character at the end of the script that is not being correctly processed (could happen if you have unix line endings in a windows environment or vice versa)?
the reason I mention this is that the error you mention says that it is
For input string: "200
I'm willing to bet that there is another quote mark at the start of the next line. If that's the case, it's trying to parse 200 and CR together as an integer. Sort out the line endings and all will be fine.
Passing argument in java through CLI
You can use commons-cli library as follows:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option host = new Option("h", "host", true, "host address");
host .setRequired(true);
options.addOption(host);
Option user = new Option("u", "user", true, "user login");
user.setRequired(true);
options.addOption(user);
Option password = new Option("p", "password", true, "user's password");
password.setRequired(true);
options.addOption(password);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("my-program", options);
System.exit(1);
return;
}
String inputHost = cmd.getOptionValue("host");
String inputUser = cmd.getOptionValue("user");
String inputPassword = cmd.getOptionValue("password");
}
}
The best CLI parser for Java
Here are some of the most popular. They are all pretty feature complete, and having used the top two I can recommend them.
Commons CLI
http://commons.apache.org/cli/Java Gems
http://code.google.com/p/javagems/picocli (with colorized usage help and autocomplete)
http://picocli.info/JArgs
http://jargs.sourceforge.net/GetOpt
http://www.urbanophile.com/arenn/hacking/download.html
EDIT: For completeness, here are some others I've come across
JOpt Simple
http://jopt-simple.sourceforge.net/Args4J
https://args4j.dev.java.net/ArgParser
http://people.cs.ubc.ca/~lloyd/java/argparser.htmlNatural CLI
http://naturalcli.sourceforge.net/TE-Code
http://te-code.sourceforge.net/JSAP
http://www.martiansoftware.com/jsap/CLAJR
http://clajr.sourceforge.net/CmdLn
http://ostermiller.org/utils/CmdLn.htmlJewelCli
http://jewelcli.sourceforge.net/JCommando
http://jcommando.sourceforge.net/Parse-cmd
http://code.google.com/p/parse-cmd/
Related Topics
How to Assert That a Certain Exception Is Thrown in Junit Tests
How to Lock a File Using Java (If Possible)
Selenium - Basic Authentication Via Url
Regex For Splitting a String Using Space When Not Surrounded by Single or Double Quotes
Difference Between Statement and Preparedstatement
What Is the Purpose of the Expression "New String(...)" in Java
How to Determine Day of Week by Passing Specific Date
How to Run Eclipse in Clean Mode? What Happens If We Do So
What Are Enums and Why Are They Useful
Including Dependencies in a Jar With Maven
What Are the Rules For Evaluation Order in Java
Random Errors When Changing Series Using Jfreechart
Getresourceasstream Returns Null
What Is the Equivalent of the C++ Pair≪L,R≫ in Java
Java Error: Comparison Method Violates Its General Contract