Reputation: 703
I have a confusion regarding the input stream
and output stream
. When do we need to use Buffered output
and input Streams
. And same with the Buffered Reader
and Buffered Writer
?
Upvotes: 0
Views: 2502
Reputation: 1753
Input stream=read bytes from file
Output stream= write bytes into file
Buffered reader= read characters from file using buffer
Buffered writer= write characters into file using buffer
buffered input stream= read bytes from file using buffer
buffered output stream= write bytes into file using buffer
Always prefer buffered stream or reader/writer as they use buffer memory before writing or reading instead of actual physical memory. They are more efficient and fast.
Stream and reader/writer has only difference in reading/writing, bytes or characters respectively.
Upvotes: 0
Reputation:
Use of Buffer and Reason: With out buffer I/O means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.
To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.
A program can convert an unbuffered stream into a buffered stream using the wrapping idiom we've used several times now, where the unbuffered stream object is passed to the constructor for a buffered stream class. Here's how you might modify the constructor invocations in the CopyCharacters example to use buffered I/O:
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
reference : Java Docs
Upvotes: 2
Reputation: 2698
Check http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html (and others) for a description on how to use them and what their use cases are. Instead of dealing with byte-wise processing of Streams you can use Buffered wrapper classes to use their methods (on a higher abstraction level) like BufferedReader.readLine()
and let the language deal with the underlying issues.
Upvotes: 0