Monday 16 December 2013

Read the File Using BufferedInputStream Example in java


import java.io.*;
public class Main {

    /**
     * @param args the command line arguments
     */

  public static void main(String[] args) {

                //create file object
                File file = new File("D://ReadFile.txt");
                BufferedInputStream bin = null;

                try
                {
                        //create FileInputStream object
                        FileInputStream fin = new FileInputStream(file);

                        //create object of BufferedInputStream
                        bin = new BufferedInputStream(fin);

                        /*
                         * BufferedInputStream has ability to buffer input into
                         * internal buffer array.
                         *
                         * available() method returns number of bytes that can be
                         * read from underlying stream without blocking.
                         */

                         //read file using BufferedInputStream
                        while( bin.available() > 0 ){

                                System.out.print((char)bin.read());
                        }

                }
                catch(FileNotFoundException e)
                {
                        System.out.println("File not found" + e);
                }
                catch(IOException ioe)
                {
                        System.out.println("Exception while reading the file... " + ioe);
                }
                finally
                {
                        //the BufferedInputStream using close method
                        try{
                                if(bin != null)
                                        bin.close();

                        }catch(IOException ioe)
                        {
                                System.out.println("Error while closing the stream : " + ioe);
                        }


                }
        }

}

output:
the file reading  reading using bufferedInputStream in java

No comments:

Post a Comment

Comment