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?
-
I'm a bit confused about your question. If you want to copy-paste a file, then you need to read it, then write it again, (or instruct the OS to do so, without buffering in Java). So you will need both Reader and Writer for this. The file reader (and writer) are endpoints in a classical IO stream of java and are only responsible to read/write to/from a file, but do not define what to do with it. BufferedReader/Writer on the other hand are stream intersegments. They can not directly be used to read/write files without an underlying stream.– TreffnonXCommented Apr 12, 2021 at 11:55
1 Answer
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.
-
1Also, if you want the concept of "lines" of input, then you'll generally need a class that implements the concept - like BufferedReader. Commented Apr 12, 2021 at 12:39