BufferedWriter in Java

Buffering can speed up IO quite a bit. Rather than writing one character at a time to the network or disk, the BufferedWriter writes a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

Constructors

BufferedWriter in Java

Methods

Screen Shot 2020-03-31 at 7.13.36 PM

package com.java.io;

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

public class BufferedWriterExample {

    public static void main(String[] args) {

        FileWriter fw = null;
        BufferedWriter bw = null;
        String data = "Testing data";

        try {
            fw = new FileWriter("/Test/TestFolder/test-file4.txt");
            bw = new BufferedWriter(fw);
            bw.write(data);
            bw.flush();
            System.out.println("Data written to File");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            // Closing the streams
            if (fw != null)
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bw != null)
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

}
Data written to File

File

Screen Shot 2020-03-31 at 7.04.21 PM

Leave a Reply

Your email address will not be published. Required fields are marked *