简体   繁体   中英

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");  
    }
}

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

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

  • when a call to one of the write methods fills the buffer 2 , 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM