Home > DeveloperSection > Blogs > Java I/O: Determining File Length

Java I/O: Determining File Length


Java Java 
Ratings:
0 Comment(s)
 166  View(s)
Rate this:

Java I/O: Determining File Length


The simplest way to determine the length of a physical file is to open it in binary mode.

·        When we use the byte-oriented classes based on InputStream and OutputStream, the file will be opened in binary mode.

·       When we use the character-oriented classes based on Reader and Writer, the file will be opened in character mode.

After opening the file, we read its contents a byte at a time until the end-of-file marker is reached. On every read operation, we increment a counter and then get the file length in the counter when the program terminates.

Program Code

The program for determining the length of a file is given in here:

import java.io.*;

 

public class FileLength {

                     public static void main(String[] args) {

                             int count = 0;

                             InputStream streamReader = null;

                             if (args.length < 1) {

                                      System.out.println("Usage: java FileLength <filename>");

                                      System.exit(0);

                             }

                             try {

                                      streamReader = new FileInputStream(args[0]);

                                      while (streamReader.read() != -1) {

                                                count++;

                                      }

                                      System.out.println(args[0] + " length = " + count);

                                      streamReader.close();

                             } catch (FileNotFoundException fe) {

                                      System.out.println("File " + args[0] + " was not found");

                                      System.exit(0);

                             } catch (IOException ie) {

                                      System.out.println("Error reading file");

                             } finally {

                                      try {

                                                streamReader.close();

                                      } catch (Exception e) {

                                                e.printStackTrace();

                                      }

                             }

                     }

}

 

 

Explanations

·         The various I/O classes are defined in the java.io package. Thus, to use I/O, we need to import the java.io package at the top of our source program:

                    import java.io.*;

·         The main function accepts the command-line arguments. When we run the program, we will need to specify the name of some file on the command line. The program determines the length of this file and prints this value on the user console. The command-line parameters are passed as arguments to the main method:

                       public static void main(String[] args) {

·         The args argument in the program is an array of String objects, where args[0] represents the first command-line argument, args[1] represents the second command-line argument, and so on.

·         In the main method, we first check whether any command-line parameters are specified while invoking the application. We do this by checking the length of the args array:

                              if (args.length < 1) {

·         If there are no command-line arguments, the program prints a message to the user on how to run the application: (The angular brackets around filename indicate that this is an optional parameter specified on the command line. If you do not specify this parameter, the program still runs):

                         System.out.println("Usage: java FileLength <filename>");

·         After printing the message, we terminate the application gracefully by calling the exit method of the System class (The parameter 0 (zero) is typically interpreted as an indication to the JVM that the program has terminated with success):

                             System.exit(0);

·         Assuming that the user specifies a command-line argument, the program will now proceed with the next statement. This statement creates an instance of the FileInputStream class by passing the first command line argument as a parameter to it. The FileInputStream class constructor opens the file specified as a parameter for reading. The file is opened in binary mode. On success, it returns a reference to the open file; we store this reference in a variable (in our example, it is called streamReader). Note that this variable is of type InputStream, which is a superclass of FileInputStream.

                            try {

                                      streamReader = new FileInputStream(args[0]);

·         As we already know, opening a file is a checked operation and must be enclosed in a try/catch block. The file-opening operation may generate a FileNotFoundException at runtime, which must be caught in the program.

·         After opening the file successfully, we call the read method of the FileInputStream class.The statement streamReader.read() reads a byte from the stream and increments the file pointer to the next position:

                while (streamReader.read() != -1) {

                               count++;

·     The file pointer indicates the current position in the stream for reading or writing. When the file pointer reaches the end-of-file, the read operation returns –1 to the caller. Therefore, in our while loop, the test condition checks for this –1. For each byte read, we increment the count variable by 1. The count variable has been set to 0 at the start of the program. When the while loop terminates, the count contains the number of bytes read, which is the length of the specified file.

·        The read operation is also a checked operation, and we must provide an appropriate error handler for it. The read operation may generate an IOException. Therefore, we provide a corresponding catch block.

·         In finally block, Note that calling the close method does not guarantee file closure; it just ensures an attempt is made to close the file. It is still possible the file may not close. The close operation itself may generate an exception. We catch this and print a detailed message to the user by calling the printStackTrace method on the exception object.

Output:

Some typical program output is shown here:

C:\360\IO\>java FileLength MindStick.xml

MindStick.xml length = 78

 

 

This execution assumes that the MindStick.xml file is available in the same folder as the one where the FileLength.class file is stored. Alternatively, we may specify a relative path with respect to the current folder of program execution or give an absolute path to the file.


Don't want to miss updates? Please click the below button!

Follow MindStick