Home Java Example Java Io How To Read File In Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

How To Read File In Java

Advertisement
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.

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

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 27, 2012

Ask Questions?    Discuss: How To Read File In Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com