Java-BufferedWriter

Buffered Input/Output

Java also supports creation of buffers to store temporarily data that is read from or written to a stream. The process is known as buffered I/O operation. A buffer sits between the program and the source or destination and functions like a filter. Buffers can be created using the BufferedWriter and BufferedReader classes.

Previous tutorials we’ve seen so far use unbuffered Input/Output(FileWriter, FileReader). This means each read or write request is handled directly by the underlying OS.

Unbuffered

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams.

The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed.

bufferedoutput

Likewise, reading text from a buffered reader may cause more characters to be read than were requested; the extra characters are stored in an internal buffer. Future reads first access characters from the internal buffer and only access the underlying reader when the buffer is emptied.

bufferedinput

 

BufferedWriter

The BufferedWriter class provides buffering to Writer instances. Buffering can speed up IO quite a bit. BufferedWriter will save up many of the little writes and send only large chunks of data to the specified Writer. This is typically much faster, especially for disk access and larger data amounts. Writing one large chunk to a file is more efficient than many small ones because each call to FileWriter.write() involves a call to the operating system, and those are slow.

Flushing and Closing Output Streams

BufferedWriter buffer writes to improve performance. Rather than sending each character to its destination as it’s written, the chararcters are accumulated in a memory buffer ranging in size from several bytes to several thousand bytes. When the buffer fills up, all the data is sent at once. The flush() method forces the data to be written whether or not the buffer is full. If you only use a stream for a short time, you don’t need to flush it explicitly. It should be flushed when the stream is closed. This should happen when you explicitly invoke the close() method.

BufferedWriter Constructors

Constructors Description
BufferedWriter(Writer out) Creates a new buffered character-output stream that uses a default-sized(8192 character) output buffer.
BufferedWriter(Writer out, int size) Creates a new buffered character-output stream that uses an output buffer of the given size.

BufferedWriter Methods

Method Description
void write(int c) This method used to write the single character.
void write(String str) This method used to write the string.
void write(String str, int off, int len) This method used to write the portion of a string.
void write(char[] cbuf) This method used to write an array of characters.
void write(char[] cbuf, int off, int len) This method used to write the portion of an array of characters.
BufferedWriter append(char c) This method appends the specified character to this writer.
BufferedWriter append(CharSequence csq) This method appends a specified character sequence to this writer.
BufferedWriter append(CharSequence csq, int start, int end) This method appends a subsequence of the specified character sequence to this writer.
void newLine() This method used to writes a line separator.
void flush() This method used to flush the stream.
void close() This method used to close the stream.

In the following program, an object of FileWriter class is first created and associated with the data file output.txt. Then, an object of BufferedWriter class is created. Subsequently, the names of four national parks are stored in the data file output.txt, one at a time, by invoking the write( ) method of the BufferedWriter class. Finally, buffered stream object is closed. Closing a bw also causes the underlying stream fw to be closed.

Program

bufferedwriter

Program Source

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args) {
        
        FileWriter fw = null;
        BufferedWriter bw = null;
        String nationalParks[] = {"1) Kruger National Park",
                                  "2) Royal Natal National Park",
                                  "3) Table Mountain National Park",
                                  "4) Kgalagadi Transfrontier Park"};
        try{
            fw = new FileWriter("output.txt");
            bw = new BufferedWriter(fw);
            int i = 0;
            
            while(i<nationalParks.length)
            {
                bw.write(nationalParks[i]);
                bw.newLine();
                i++;
            }
        }catch(IOException io)
        {
            System.out.println("Exception : "+io);
            
        }finally{
            
            try{
                bw.close();
            }catch(IOException io)
            {
                System.out.println("Exception : "+io);
            }
        }
    }
}

Leave a Comment