Wednesday, May 9, 2012

How to read file in Java using BufferedInputStream with example

Example to demonstrate how to read a file in Java using BufferedInputStream and DataInputStream classes with example.
In this example readLine() method is used to read each line from file.


import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileExample
{
    public static void main(String[] args)
    {
        File file = new File("D:\\db\\fileTest\\file1.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try 
        {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            while (dis.available() != 0)
            {
                String lineString=dis.readLine();
                System.out.println(lineString);
            }
         } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally //finally closing file
        {
            try 
            {
                fis.close();
                bis.close();
                dis.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

No comments:

Post a Comment