javabufferedreaderfilereaderfilewriterbufferedwriter

Buffer and File in Java


I'm new to java and I want to ask what's the difference between using FileReader-FileWriter and using BufferedReader-BufferedWriter. Except of speed is there any other reason to use Buffered? In a code for copying a file and pasting its content into another file is it better to use BufferedReader and BufferedWriter?


Solution

  • The short version is: File writer/reader is fast but inefficient, but a buffered writer/reader saves up writes/reads and does them in chunks (Based on the buffer size) which is far more efficient but can be slower (waiting for the buffer to fill up).

    So to answer your question, a buffered writer/reader is generally best, especially if you are not sure on which one to use.

    Take a look at the JavaDoc for the BufferedWriter, it does a great job of explaining how it works:

    In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
    

    will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.