Parsing command line argument in java

How do I parse command line arguments in Java?

To parse command line arguments in Java, you can use the main() method of your application’s entry point class.

The main() method is the entry point of a Java program and is called by the JVM when the program starts. It takes an array of strings as an argument, which represents the command line arguments passed to the program.

Here is an example of how to parse command line arguments in the main() method:

public class MyApplication < public static void main(String[] args) < for (int i = 0; i < args.length; i++) < String arg = args[i]; if (arg.equals("-h")) < printUsage(); >else if (arg.equals("-f")) < String fileName = args[++i]; // process file > else < // invalid argument > > > private static void printUsage() < // print usage information > >

In this example, the main() method iterates over the array of command line arguments and checks for the presence of the -h and -f arguments. If the -h argument is found, the printUsage() method is called to print usage information. If the -f argument is found, the next argument is assumed to be the file name and is processed.

You can also use a library such as Apache Commons CLI to parse command line arguments in a more flexible and user-friendly way.

I hope this helps. Let me know if you have any questions.

Читайте также:  Java load class forname

Источник

Simple Java Command Line Argument Parser Implementation

Here, we will create a Custom CommandLineParser class to parse the arguments passed via command line in Java.
Let’s first see the sample entry point for Java program.

public class MyProgram public static void main(String args[])  System.out.println("This is my program."); > > 

Ever wondered why do we need to pass array of strings as arguments in main method of Java?
It’s for the command line arguments. When you run your Java program from command line:

It takes “Oshan” as argument. So, if you want your program to access this String , you can access it using the array of String passed in the main method.

// inside main method //Prints "My name is Oshan" System.out.println("My name is ", args[0]); 

You can pass initial configuration you want your Java program to follow via command line arguments. For example:

## if you want to send file path java MyProgram -filePath file1.txt ## if you want to send multiple file paths java MyProgram -filePath file1.txt file2.txt ## or, if you just want to send flags java MyProgram -noprint 

By default, Java takes these each string as argument and cannot differentiate between argument names, values, or flags. So, today, we’ll write a simple program that will parse the arguments passed through command line. This way we don’t have to hard code the arguments values as args[1] or args[2] in our program. Instead, we will be able to see the argument list and choose values using argument names rather than array of string.

import java.util.HashMap; import java.util.HashSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; public class CommandLineParser  List String> args = new ArrayList<>(); HashMapString, ListString>> map = new HashMap<>(); SetString> flags = new HashSet<>(); CommandLineParser(String arguments[])  this.args = Arrays.asList(arguments); map(); > // Return argument names public SetString> getArgumentNames()  SetString> argumentNames = new HashSet<>(); argumentNames.addAll(flags); argumentNames.addAll(map.keySet()); return argumentNames; > // Check if flag is given public boolean getFlag(String flagName)  if(flags.contains(flagName)) return true; return false; > // Return argument value for particular argument name public String[] getArgumentValue(String argumentName)  if(map.containsKey(argumentName)) return map.get(argumentName).toArray(new String[0]); else return null; > // Map the flags and argument names with the values public void map()  for(String arg: args)  if(arg.startsWith("-"))  if (args.indexOf(arg) == (args.size() - 1))  flags.add(arg.replace("-", "")); > else if (args.get(args.indexOf(arg)+1).startsWith("-"))  flags.add(arg.replace("-", "")); > else  //List of values (can be multiple) ListString> argumentValues = new ArrayList<>(); int i = 1; while(args.indexOf(arg)+i != args.size() && !args.get(args.indexOf(arg)+i).startsWith("-"))  argumentValues.add(args.get(args.indexOf(arg)+i)); i++; > map.put(arg.replace("-", ""), argumentValues); > > > > > 

Now, you can add the above class to any program you want and easily parse the values.
Let’s try with a simple program:

public class MyProgram  public static void main (String args[])  CommandLineParser clp = new CommandLineParser(args); > > 

Make sure you include the CommandLineParser class in the classpath when you compile your program.

javac -classpath /pathToTheCommandLineParserClass MyProgram.java java MyProgram.java -name Oshan -prints 3 -test 

Now, in our program you can easily get these values and use it.

// inside main method String name = clp.getArgumentValue("name"); int prints = Integer.parseInt(clp.getArgumentValue("prints")); boolean isTest = clp.getFlag("test"); if(isTest) System.out.println("This is only a test"); for(int i = 0; i  prints; i++)  System.out.print(name+" "); > 

Output of the above program will be:

This is only a test Oshan Oshan Oshan 

You can also use method getArgumentNames to see the passed arguments names.
I recently encountered a problem which made me write this custom CommandLineParser . Obviously, you can modify this to fit your requirements or go with traditional approach. But, making such class removes the ambiguity when multiple arguments are passed via command line.
I hope you find this useful.

Источник

Command-Line Arguments

A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:

When an application is launched, the runtime system passes the command-line arguments to the application’s main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : «friends.txt» .

Echoing Command-Line Arguments

The Echo example displays each of its command-line arguments on a line by itself:

The following example shows how a user might run Echo . User input is in italics.

java Echo Drink Hot Java Drink Hot Java

Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

java Echo "Drink Hot Java" Drink Hot Java

Parsing Numeric Command-Line Arguments

If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as «34», to a numeric value. Here is a code snippet that converts a command-line argument to an int :

int firstArg; if (args.length > 0) < try < firstArg = Integer.parseInt(args[0]); >catch (NumberFormatException e) < System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); >>

parseInt throws a NumberFormatException if the format of args[0] isn’t valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.

Источник

Argparse4j — The Java command-line argument parser library¶

Argparse4j is a command line argument parser library for Java based on Python’s argparse module.

Argparse4j is available in Maven central repository:

  net.sourceforge.argparse4j argparse4j 0.9.0  

IMPORTANT: When upgrading, read Migration. There is an important change in 0.5.0 which might break your code. The documentation describes the change and how to migrate from earlier versions.

There are still missing features which exist in argparse but not in argparse4j, but there are also new features which only exist in argparse4j.

Here is summary of features:

  • Supported positional arguments and named arguments.
  • Variable number of arguments.
  • Generates well formatted line-wrapped help message.
  • Suggests named arguments/sub-command if unrecognized arguments/sub-command were given, e.g.:
unrecognized argument '--tpye' Did you mean: --type 

Requirements¶

Java 8 or higher is needed.

The main JAR contains module information for the Java Module System. The module name is net.sourceforge.argparse4j .

Building¶

To build you need Java 9 or higher, and Maven 3.2.3 or higher.

The primary documentation is done using Sphinx. You need Sphinx to run mvn site .

To see how to use argparse4j, see The Argparse4j User Manual . See also Examples .

Contents¶

  • The Argparse4j User Manual
    • Examples
    • ArgumentParser objects
    • The ArgumentParser.addArgument() method
    • The ArgumentParser.parseArgs() method
    • The Namespace object
    • Other utilities
    • Extensions
    • CJK line-wrap example
    • Clojure example
    • To 0.5.0:
    • To 0.8.0:

    Demo¶

    Here is the working demo program to calculate checksum. Argparse4j is used to parse command line arguments (Java 7 required to compile this source code):

    import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; public class Checksum  public static void main(String[] args)  ArgumentParser parser = ArgumentParsers.newFor("Checksum").build() .defaultHelp(true) .description("Calculate checksum of given files."); parser.addArgument("-t", "--type") .choices("SHA-256", "SHA-512", "SHA1").setDefault("SHA-256") .help("Specify hash function to use"); parser.addArgument("file").nargs("*") .help("File to calculate checksum"); Namespace ns = null; try  ns = parser.parseArgs(args); > catch (ArgumentParserException e)  parser.handleError(e); System.exit(1); > MessageDigest digest = null; try  digest = MessageDigest.getInstance(ns.getString("type")); > catch (NoSuchAlgorithmException e)  System.err.printf("Could not get instance of algorithm %s: %s", ns.getString("type"), e.getMessage()); System.exit(1); > for (String name : ns.String> getList("file"))  Path path = Paths.get(name); try (ByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ);)  ByteBuffer buffer = ByteBuffer.allocate(4096); while (channel.read(buffer) > 0)  buffer.flip(); digest.update(buffer); buffer.clear(); > > catch (IOException e)  System.err .printf("%s: failed to read data: %s", e.getMessage()); continue; > byte md[] = digest.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0, len = md.length; i  len; ++i)  String x = Integer.toHexString(0xff & md[i]); if (x.length() == 1)  sb.append("0"); > sb.append(x); > System.out.printf("%s %s\n", sb.toString(), name); > > > 
    $ java Checksum -h usage: Checksum [-h] [-t ] [file [file . ]] Calculate checksum of given files. positional arguments: file File to calculate checksum named arguments: -h, --help show this help message and exit -t , --type Specify hash function to use (default: SHA-256) $ java Checksum file1.cc file1.h 6bd85bf4b936bc8870c70bea04cd12d4fe3745934f511e6e188d718d32154a79 file1.cc 839ef370cbd54f62985bac7b974cc575eaaa24a8edd6ae7787cfc71829ceda40 file1.h $ java Checksum --tpye file1.cc usage: Checksum [-h] [-t ] [file [file . ]] Checksum: error: unrecognized arguments: --tpye Did you mean: --type $ java Checksum -t SHA1 file1.cc 20bada64dde97b98faaba09ebbfdb70af71476f1 file1.cc 

    Источник

Оцените статью