Read File From Command Line With Java

Command line interfaces are a great option if your program is primarily used past developers or if it needs to exist accessed programmatically through bash scripts. In this tutorial – directed at Coffee developers – you will learn why command line arguments are useful, how to apply command line arguments in Java, and discover some examples that you can use to build your ain command line applications.

A Java command line program accepts values from the command line during execution. With command line programs, yous do non demand a graphical user interface (GUI) to interact with or pass inputs into your program. Control line programs are useful if you use SSH to run commands on a remote organisation or if your program is intended to exist run via automation scripts that don't need a GUI.

Java control line arguments are arguments that are passed to your plan via a terminal or crush command. They make your Java program more configurable past giving users or scripts running your software a way to specify input parameters at run time.

In this detailed tutorial, you lot'll learn how to:

  • Create a uncomplicated Coffee command line application
  • Utilise single and multiple arguments in a Java CLI application
  • Support flags and CLI responses in your command line arguments
  • Use two popular third-party libraries to handle control line arguments
  • Utilize an IDE to run a Java command line application

A Java Control Line Application

The main() method is typically the entry point for a Java class. The JVM passes the control line argument through the String[] args parameter of the main() method, then you tin can fetch these arguments by accessing this parameter.

Permit's look at a simple Coffee command line application. To compile the plan from control line, use javac where SimpleCommandLinePgm.coffee is the name of your Coffee file, i.eastward:

javac SimpleCommandLinePgm.coffee

This will compile your Coffee application and create a .class file, which can be executed with the java command. The total code of your java awarding might look something similar this:

          Class SimpleCommandLinePgm {   public static void main(String[] args) {     System.out.println("This is a simple control line plan!");     Organisation.out.println("Your Control Line arguments are:"); // loop through all arguments and impress it to the user      for (String str: args) {       Organisation.out.println(str);     }   } }        

Executing a Java Command Line Script with One Argument

Command Line arguments typically follow the name of the programme when information technology is executed, so to execute your newly compiled class, run the post-obit from your terminal:

          java SimpleCommandLinePgm one        
  • SimpleCommandLinePgm is the name of the compiled Coffee programme without the .java extension.
  • ane is your first control line argument to the plan

You should see the post-obit output:

This is a simple command line programme! Your Command Line arguments are: one

Executing a Java Command Line Script with Multiple Arguments

Now that you've executed a Coffee command line class with one argument, permit's look at how this changes with multiple control line arguments:

          coffee SimpleCommandLinePgm one two three four        

This command looks about the aforementioned, only equally you lot can see, in that location are now four arguments after the name of the program (1 2 three 4). Each item in your listing of command line arguments is separated by space.

This time, you'll see something like this:

This is a unproblematic command line programme! Your Command Line arguments are: one ii three four

Now that you've seen how to apply control line arguments in your Coffee applications, you have a good starting point, simply these examples require you to pass arguments in social club. What if y'all want your script to accept named values as input?

In the next section, you'll encounter how to create and execute a Java programme that accepts and parses command line arguments as key-value pairs.

Executing a Coffee Command Line Script with Named Arguments

Allowing users to enter named arguments into a Java command line application makes your program much more flexible. It allows users to leave out some arguments, and it makes your interface more than intuitive equally users running the application can tell what each argument might practise based on the key proper noun.

By default, Coffee doesn't accept key-value pairs via the CLI. However, the arguments can be passed using the -D parameter, which passes the fundamental-value pair arguments every bit arguments to the JVM itself.

This class shows how the key value pair arguments can be accessed from your Java program using the system.getProperty() method:

          public class AdvancedCommandLinePgm {   public static void principal() {     System.out.println("This is an avant-garde command line program!"); // Get the value using the Organization.get Property and print it.      System.out.println("Username is: " + Organisation.getProperty("userName"));   } }        

Subsequently you compile the program, y'all should be able to run information technology with a control like this:

          java -Dusername=Vikram AdvancedCommandLinePgm        

And the output will be:

          This is an advanced control line programme! Username is: Vikram        

While this method of named arguments in a Java command line program works, information technology's not the most elegant solution. In the next section, you lot'll acquire how to utilize 2 different tertiary-party libraries to attain these aforementioned tasks without writing quite as much code yourself.

3rd-Party Libraries for Handling Java Command Line Arguments

Using third-political party libraries tin can relieve yous a lot of fourth dimension considering the library handles validation and parsing. For example, you can make a parameter mandatory by simply setting a boolean value – yous don't need to write code to check if it'southward been provided. The library will and then throw an error with an appropriate message if the mandatory argument has not been supplied. Third-party libraries tin can too display help messages without the need for you to write more than code.

In this department, we'll expect at two tertiary-party libraries that are unremarkably used for creating Java control line applications: PicoCli and Apache Commons CLI.

Using PicoCli to Parse Coffee Control Line Arguments

PicoCli is a unmarried-file framework that allows you to create a Java program with nigh zero code for handling command line arguments. It supports multiple control line syntax styles, including POSIX, GNU, MS-DOS, and information technology can generate highly customizable help letters with ANSI styles and colors to highlight important elements.

To use the PicoCli, you need the jar in your buildpath, classpath, or Maven repository (depending on your project configuration).

PicoCli can be implemented using the Callable or Runnable interfaces, which makes it easy for you to create a runnable Coffee plan. Here'southward an instance of a simple PicoCli class:

          @Control(proper noun = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile data.")  form PicoCliSamplePgm implements Runnable { }        

The note @Command for the class denotes that this is a command line plan. Hither, I'1000 using several attributes for the @Command annotation:

  • name – Name of the command line program
  • mixinStandardHelpOptions – Flag to announce whether Usage help and Version help should be added to your program equally Mixin
  • version – Version information of the command line program, to display while printing the usage assist
  • description – Description of the command line program, to brandish while printing the usage assist

PicoCli supports both named and positional arguments. For example, the following annotation shows how named arguments (chosen options by PicoCli) are defined:

          @Pick(names = { "-f", "--firstname" }, required = truthful, clarification = "First Name of the user") private String firstName = "Outset Name";        

Positional arguments (called parameters) don't have names and are mandatory past default. This example shows how you tin ascertain a positional parameter in PicoCli:

          @Parameters(index = "0") individual String land;        

Y'all can read more about PicoCli'south options and parameters in their documentation.

To employ the command line arguments divers by PicoCli, yous only admission them every bit variables within your Java form'due south run() method. Here's a complete example of a Java class that uses PicoCli to parse and display user profile information passed via the command line:

          @Command(name = "userprofileinfo", mixinStandardHelpOptions = true, version = "User Profile Information V1.0", description = "Displays the User profile information.") course PicoCliSamplePgm implements Runnable {      @Selection(names = {             "-f",              "--firstname"     },              required = true, clarification = "Offset Proper name of the user")     private String firstName = "First Name";     @Choice(names = {             "-l",             "--lastname"     },             required = truthful, clarification = "Last name of the user")     private Cord lastName = "Last Name";     @Option(names = {             "-e",             "--e-mail"     },             required = truthful, clarification = "email id of the user")     individual String email = "email"; // Positional Parameters     @Parameters(index = "0")     private String country;     @Selection(names = {             "-m",             "--mobilenumber"     },             required = false, description = "Mobile Number of the user")     private String mobileNumber;      // This case implements Runnable, then parsing, error handling, and help messages tin can exist done with this line:     public static void master(String... args) {         int exitCode = new CommandLine(new PicoCliSamplePgm()).execute(args);         Organisation.exit(exitCode);     }      @Override     public void run() { // your business logic goes here...         Organization.out.println("User First Name is: " + firstName);         System.out.println("User Last Proper name is: " + lastName);         System.out.println("User Email is: " + e-mail);         if (mobileNumber != naught) {             System.out.println("User Mobile Number is: " + mobileNumber);         }         if (country != nada && !country.isEmpty()) {             System.out.println("(Positional parameter) User's land is: " + country);         }     } }        

Execute this program via your command line in the following way:

          # Note: Depending how yous include the PicoCli library, your command may vary.  java -cp "myapp.jar;picocli-4.v.2.jar" PicoCliSamplePgm -f Vikram -l Aruchamy -eastward name@electronic mail.        

You'll encounter output similar the post-obit:

          User First Name is: Vikram  User Concluding Name is: Aruchamy  User Email is: proper noun@email.com  User Mobile Number is: 123456789 (Positional parameter)  User's state is: India        

In that location are a lot of other things y'all can exercise with PicoCli, so be sure to refer to their extensive documentation for more.

Using Apache Commons CLI to Parse Coffee Command Line Arguments

Apache Commons CLI is some other commonly used library in Java for command line parsing. It'southward a good choice if you just demand basic command line functionality and are already using other Apache libraries like Commons IO.

To use the Apache Eatables CLI, you need the jar in your buildpath, classpath, or the Maven repository.

You can define command line options using the Options and Option objects available in Commons CLI. Options offers a list to hold all your programme's options, while Option lets yous ascertain the characteristics of each parameter individually.

To parse control line parameters, Commons CLI uses the DefaultParser implementation of the CommandlineParser interface. DefaultParser has a method called parse() which accepts the options object and the args from the command line. Finally, you lot tin can use the HelpFormatter to impress the aid information to the user.

The beneath example shows y'all a complete example of the Apache Eatables CLI:

          public course CommonsCliPgm {     public static void principal(String[] args) throws Exception {         Options options = new Options();         Option name = new Option("f", "proper noun", true, "First Proper noun");         name.setRequired(true);         options.addOption(proper name);         Option lastName = new Selection("l", "lastname", true, "Last Name");         lastName.setRequired(true);         options.addOption(lastName);         Option email = new Option("e", "email", true, "Email");         email.setRequired(truthful);         options.addOption(email);         Option mobileNumber = new Option("m", "mobilenumber", true, "Mobile Number");         mobileNumber.setRequired(imitation);         options.addOption(mobileNumber);         HelpFormatter formatter = new HelpFormatter();         CommandLineParser parser = new DefaultParser();         CommandLine cmd;         endeavour {             cmd = parser.parse(options, args);         } grab (ParseException e) {             Organization.out.println(due east.getMessage());             formatter.printHelp("User Profile Info", options);             System.leave(ane);             render;         }         System.out.println("User Offset Proper name is: " + cmd.getOptionValue("proper noun"));         Organisation.out.println("User Concluding Name is: " + cmd.getOptionValue("lastname"));         System.out.println("User Email is: " + cmd.getOptionValue("e-mail"));         if (cmd.hasOption("thousand")) {             System.out.println("User Mobile Number is: " + cmd.getOptionValue("mobilenumber"));         }     } }        
Now y'all can run the programme with the optional          -m          parameter:
          java CommonsCliPgm -f Vikram -l Aruchamy -e proper name@email.com        

And the output will exist:

          User Get-go Name is: Vikram  User Last Name is: Aruchamy  User Electronic mail is: proper name@email.com  User Mobile Number is: 123456789        

Or without the optional parameter:

          java CommonsCliPgm -f Vikram -fifty Aruchamy -e proper name@e-mail.com        

Which will output the following:

          User Showtime Proper name is: Vikram  User Final Name is: Aruchamy  User Email is: name@electronic mail.com        

As y'all can come across, both the Apache Commons CLI and PicoCli make working with control line arguments in Java much easier and more robust. While yous might not need them for very elementary internal CLI scripts, it'southward probably a good thought to consider using one of these options if you desire help docs, mistake handling, and both optional and required statement back up.

Using an IDE with Java Command Line Arguments

Using an IDE to develop your program can provide significant advantages. Typically, IDEs give yous:

  • Motorcar-complete and suggestions to speed up your development
  • Line-by-line debugging (rather than using System.out.println())
  • Version command system integration that makes it easier to track changes to your lawmaking

In this department, you'll learn how to test and run command line scripts using the Eclipse IDE and IntelliJ Idea. This section assumes you lot've already set upward and have a working command line program (like one of the ones above).

Command Line Arguments in Eclipse IDE

In Eclipse, right-click on the class you want to run. In the context menu, select Run Equally -> Java Application. Information technology will run the program:

Running a Java command line class in Eclipse

If your control line program requires specific arguments, y'all'll see an fault saying that command line parameters are missing. Behind the scenes, Eclipse will create a configuration. To add your arguments, right-click again and select Run -> Run Configuration.

Eclipse will show you all the run configurations available in the workspace. Select the class name on the left side and enter your command line parameters, as shown in the beneath epitome.

Running a Java command line class with arguments in Eclipse

Click Run. You'll see output based on your command line parameters.

          User First Name is: Vikram  User Last Name is: Aruchamy  User Email is: proper name@email.com  User Mobile Number is: 123456798  (Positional parameter) User'south country is: Bharat        

Control Line Arguments in IntelliJ

In IntelliJ, the procedure is similar. Right-click on the class, and in the context carte du jour, select Run PicoCliSamplePgm.Main():

Running a Java command line class in IntelliJ

It will run the program and if arguments are required, bear witness an error. Now IntelliJ has created a configuration, so you can select Run -> Run Configurations. Select the class name on the left side equally shown below and enter your command line parameters in the Programme Arguments option. Click Ok.

IntelliJ Command Line Arguements

Run your program again using the Run option in the right-click context bill of fare. You'll see output based on your command line parameters.

Decision

In this tutorial, you've seen how to create a simple Java command line programme that parses arguments and named options. You've learned how to create command line programs using PicoCli and the Apache Commons CLI package, and finally, how to utilize command line arguments with both the Eclipse and IntelliJ IDEs. Armed with this knowledge, yous should be able to create robust control line applications in Java that use a multifariousness of optional, required, and named arguments.׳

zieglercronts.blogspot.com

Source: https://lightrun.com/java/java-tutorial-java-command-line-arguments/

0 Response to "Read File From Command Line With Java"

ارسال یک نظر

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel