Write a program to display the contents of a file. The filename is given as command line argument.
Command line argument :
When running a program as a command, we can specify one or more options with the program name. These are called command line arguments.
e.g.
java myprogram hello world
Here hello and world are command line arguments. When we define our main() method as ..main(String args[]), the arguments are stored args[0], args[1] and so on.
FileReader class
FileReader is a class for reading character streams. It takes the file name to be opened for reading as constructor parameter. You can read one character at a time using read() method. When end of file is reached, the read() returns -1.
FileReader reader = new FileReader("a.txt");
char ch ='';
while ( (ch=reader.read())!=-1)
System.out.print(ch);
Now let us see the complete program.
Observe that file name is args[0]. If we run this program as
java filedisplay one.txt
then one.txt is args[0] - the first command line argument.
The program when executed will display the contents of the file on the console.
import java.io.*; public class filedisplay { public static void main(String args[]) throws IOException { String filename1 = args[0]; FileReader in = null; try { in = new FileReader(filename1); int c; while ((c = in.read()) != -1) { System.out.print((char)c); } }finally { if (in != null) { in.close(); } } } }
Observe that file name is args[0]. If we run this program as
java filedisplay one.txt
then one.txt is args[0] - the first command line argument.
The program when executed will display the contents of the file on the console.
Comments
Post a Comment