A Basic ReaderWriter Example Modified ReaderWriter Example

J.E.D.I.

12.5.3 Filter Writer Classes

To add functionalities to the basic Writer classes, you can use the filter stream classes. Here are some of these classes: Filter Writer Classes BufferedWriter Allows buffering of characters in order to provide for the efficient writing of characters, arrays, and lines. FilterWriter For writing filtered character streams. OutputStreamWriter Encodes characters written to it into bytes. PrintWriter Prints formatted representations of objects to a text-output stream. Table 50: Filter Writer classes

12.6 A Basic ReaderWriter Example

The succeeding example uses the FileReader and the FileWriter class. In this example, the program reads from a file specified by the user and copies the content of this file to another file. import java.io.; class CopyFile { void copyString input, String output { FileReader reader; FileWriter writer; int data; try { reader = new FileReaderinput; writer = new FileWriteroutput; while data = reader.read = -1 { writer.writedata; } reader.close; writer.close; } catch IOException ie { ie.printStackTrace; } } public static void mainString args[] { String inputFile = args[0]; String outputFile = args[1]; CopyFile cf = new CopyFile; cf.copyinputFile, outputFile; } } Try out the program yourself and observe what happens to the files manipulated. Introduction to Programming II Page 165 J.E.D.I. Using temp.txt from our previous example, heres the result when we pass temp.txt as the inputFile and temp2.txt as the outputFile: Figure 12.1: Sample output for CopyFile Introduction to Programming II Page 166 J.E.D.I.

12.7 Modified ReaderWriter Example

The succeeding example is similar to the previous example but is more efficient. Instead of reading and writing to the stream one at a time, characters read are first stored in a buffer before writing characters line per line. The program uses the technique of stream chaining wherein the FileReader and the FileWriter class are decorated with the BufferedReader and the BufferedWriter class, respectively. import java.io.; class CopyFile { void copyString input, String output { BufferedReader reader; BufferedWriter writer; String data; try { reader = new BufferedReadernew FileReaderinput; writer = new BufferedWriternew FileWriteroutput; while data = reader.readLine = null { writer.writedata, 0, data.length; } reader.close; writer.close; } catch IOException ie { ie.printStackTrace; } } public static void mainString args[] { String inputFile = args[0]; String outputFile = args[1]; CopyFile cf = new CopyFile; cf.copyinputFile, outputFile; } } Compare this code with the previous one. What is the result of running this program? Heres a sample output of this version of CopyFile. Introduction to Programming II Page 167 J.E.D.I. Figure 12.2: Sample output for CopyFile Introduction to Programming II Page 168 J.E.D.I.

12.8 InputStream Classes