Java-BufferedReader

BufferedReader

The BufferedReader class possesses the functionality of reading buffers of characters from a file. In the following program, an object of FileReader class is first created and associated with the data file output.txt. Then, an object of BufferedReader class is created. Subsequently, the names of five national parks, which have been written into the data file output.txt in previous program, are retrieved, one by one, by invoking the readLine( ) method of the BufferedReader class, and then displayed. Finally, both the file streams are closed.

BufferedReader Constructors

Constructors Description
BufferedReader(Reader in) Creates a buffering character-input stream that uses a default-sized input buffer.
BufferedReader(Reader in, int size) Creates a buffering character-input stream that uses an input buffer of the specified size.

BufferedReader Methods

Method Description
int read() Reads a single character.
int read(char[] buf) Reads characters into an array.
int read(char[] buf, int off, int len) Reads characters into a portion of an array.
String readLine() Reads a line of text.
boolean ready() Tells whether this stream is ready to be read.
boolean markSupported() Tells whether this stream supports the mark() operation, which it does.
void mark(int readAheadLimit) Sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid.
void reset() Resets the stream to the most recent mark.
long skip(long n) Skips over and discards n characters of data from the input stream.
void close() Closes the stream and releases any system resources associated with it.

Program

Program Source

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args) {
        
        FileReader fr = null;
        BufferedReader br = null;
        
        try{
            fr = new FileReader("output.txt");
            br = new BufferedReader(fr);
            String getline = null;
            while((getline=br.readLine())!=null)
            {
                System.out.println(getline);
            }
        }catch(IOException io)
        {
            System.out.println("Exception : "+io);
            
        }finally{
            
            try{
                br.close();
            }catch(IOException io)
            {
                System.out.println("Exception : "+io);
            }
        }
    }
}

Leave a Comment