by Dinesh Thakur

A Java application can accept any number of arguments from the command line. Command-line arguments allow the user to affect the operation of an application.

The user enters command line arguments when invoking the application and specifies them after the name of the class to run. For example, suppose our Java application name is ReadingFileFileInputStream which displays the contents of a file. To display the contents of the file ecomputernotes.bat, we execute the program as :

java ReadingFileFileInputStreamecomputernotes.bat

In the Java language, when we invoke an application, the runtime system passes the command line arguments to the application's main method via an array of Strings: args. Each element in this string array args contains one of the command line arguments sent through command line. We can find out the number of command line arguments with the array's length attribute:

n = args.length;

In Java, name of the application is already known as it is the name of the class in which the main method is defined. So the Java runtime system does not pass the class name to the main method. Rather, it passes only the items on the command line that appear after the class name.


class ReadingFileFileInputStream
         public static void main(String args[]) throws IOException
             int i;
             FileInputStream fp;
                  fp=new FileInputStream(args[0]);
                     catch(FileNotFoundException e)
                            System.out.println("File cannot be found");
                                if(i !=-1)
                              }while(i !=-1);

Reading File in Java