Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Attaching / Stacking Streams

Reading/writing files a character at a time is inefficient.

An easy way to improve performance: Use Java's capability to attach one stream to another.

Source: examples/BufferedCopy.java



/** Copy file contents using buffering
**/
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
public class BufferedCopy {
public static void main(String[] args) {
if (args.length != 1)
System.out.println("usage: BufferedCopy file_to_copy");
else {
BufferedCopy obj = new BufferedCopy();
try {
obj.makeCopy(args[0]);
}
catch (IOException e) {
System.out.println(e);
}
}
}
 
public void makeCopy(String filename) throws IOException {
FileReader fr = new FileReader(filename);
BufferedReader bufIn = new BufferedReader(fr);
 
FileWriter fw = new FileWriter(filename + ".copy");
BufferedWriter bufOut = new BufferedWriter(fw);
 
// An alternative way to write the previous four lines is:
// BufferedReader bufIn = new BufferedReader( new FileReader(args[0]));
// BufferedWriter bufOut = new BufferedWriter( new FileWriter(filename + "copy));
// since fr and fw are only used in the BufferedReader/Writer
// constructors.
 
String s;
 
// Read and write lines of text (through buffers)
while (true) {
s = bufIn.readLine(); // trims end of line character
if (s == null)
break;
bufOut.write(s);
bufOut.newLine(); // adds an end of line character
}
 
// Flush anything remaining and release resouurces
bufIn.close();
bufOut.close();
bufIn = null;
bufOut = null;
}
}

Copy of a ~ 1/2 megabyte file :
CopyChars - 42 seconds
BufferedCopy - < 8 seconds

Buffered input also enables some other capabilities that would not be possible otherwise, e.g., readLine().

Question: Why isn't readLine() implemented for other Stream and Reader classes?

Other Stream and Reader/Writer classes provide other useful filters.

Question: What's the point of the alternative way of creating in and out?


Top
Previous Next
jwd