Chukwudi Ogbonna
Chukwudi Ogbonna

Reputation: 3

Buffered Readers and Writers

So I have an issue, I read in a textbook, that the buffer only writes to the text file when its full and only reads from the text file when its empty So assuming I want to write just one String "James", surely that wouldn't make the buffer full, so why does it still get written to a file testout.txt

package com.javatpoint;  

import java.io.*;

public class BufferedWriterExample {

    public static void main(String[] args) throws Exception {     
        FileWriter writer = new FileWriter("D:\\testout.txt");  
        BufferedWriter buffer = new BufferedWriter(writer);  
        buffer.write("Welcome to javaTpoint.");  enter code here
        buffer.close();  
        System.out.println("Sucenter code herecess");  
    }
}

Upvotes: 0

Views: 57

Answers (1)

Stephen C
Stephen C

Reputation: 719248

I read in a textbook, that the buffer [in a BufferedWriter] only writes to the text file when it is full ...

That is incorrect1. In fact, a BufferedWriter will write to the Writer that it wraps:

  • when a call to one of the write methods fills the buffer2, OR
  • when you call bw.flush(), OR
  • when you call bw.close().

These will typically write data to the file. (But not always. It depends on the behavior of the wrapped Writer.)

So the reason that all of the data is written in your example is that you are calling buffer.close().


... and [a BufferedReader] only reads from the text file when its empty.

This is correct, but not relevant to the rest of your question.


1 - You probably misread the text book.

2 - Actually it is a bit more complicated than this because a write(char[], ...) call that writes a large enough number of characters will first flush the buffer, and then write directly from the char[] to the wrapped stream. It bypasses the buffer to avoid an unnecessary copy.

Upvotes: 3

Related Questions