Java Reference
In-Depth Information
streams can be used to wrap around other streams. They provide a dedicated space in memory (a
buffer) to store data in an efficient manner, and will request time-expensive operations only if neces-
sary (such as when the buffer is full and ready to be written to disk).
Four buffer classes exist which can be wrapped around a byte or character input/output stream:
BufferedInputStream , BufferedOutputStream , BufferedReader , and BufferedWriter . The latter
two classes are especially helpful when dealing with text files, as they allow you to work with data in a
line-oriented manner. The following Try It Out once again shows the file copier example rewritten.
Copying and Showing Files Line by Line with Buffered Streams
try it out
In this Try It Out, you will copy a grocery list using buffered character streams.
1.
You will modify the FileCopier class created earlier. Refer to the earlier Try It Out if you have
not done so already. Make sure the groceries.txt file is still present.
2.
Edit the FileCopier class to look as follows:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileCopier {
public static void main(String[] args) {
try (
Reader in = new BufferedReader(
new FileReader("groceries.txt"));
Writer out = new BufferedWriter(
new FileWriter("groceries (copy).txt"));
) {
String line;
while ((line = in.readLine()) != null) {
out.write(line + System.lineSeparator());
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.
Execute the program. You'll see that it behaves similarly as before.
How It Works
Here's how it works:
1.
We're now using BufferedReader and BufferedWriter classes here to open the original file as
a data source and a new file as a destination. Note that these classes wrap around normal Reader
and Writer classes (just as BufferedInputStream and BufferedOutputStream wrap around
InputStream and OutputStream classes).
Search WWH ::




Custom Search