How To Read File In Java

In this section we will discuss about about how data of a file can be read in Java.

How To Read File In Java

In this section we will discuss about about how data of a file can be read in Java.

How To Read File In Java

How To Read File In Java

In this section we will discuss about about how data of a file can be read in Java.

A file can contain data as bytes, characters, binary data etc. To read a file in Java we can use following of the classes :

for reading byte/s data FileInputStream
for reading character/s data FileReader

FileInputStream reads the raw bytes stream and FileReader reads the character streams. To read data from the file we can use the read() method defined by the classes itself or inherited from their parent class.

Example

This example demonstrates that how to read a file in java. To read a file there must be a file which contents can be read so, I have created a file named test.txt, contains some data, in the current directory. Then I have created a Java Program to read the data of a file and used the FileInputStream class of java.io package. To read the file contents used read() method of the FileInputStream.

Source Code

JavaReadFileExample.java

import java.io.FileInputStream;
import java.io.IOException;

public class JavaReadFileExample
{
    public static void main(String args[])
      {
          FileInputStream fis = null;
          try
            {
                fis = new FileInputStream("test.txt");
                int r;
                while((r = fis.read()) != -1)
                   {
                       System.out.print((char)r);
                   }
            }
          catch(IOException ioe)
            {
                System.out.println(ioe);
            }
          finally
            {
                if(fis != null)
                 {
                    try
                      {
                          fis.close();
                      }
                    catch(Exception e)
                      {
                         System.out.println(e);
                      }
                  }
            }// finally closed
      }// main closed
}// class closed

Output

When you will execute the above example you will get the output as follows :

But when you will execute the above example and the specified file is not available in the directory then the output will be as follows :

Download Source Code