A Basic InputStreamOutputStream Example Modified InputStreamOutputStream Example

J.E.D.I.

12.10 A Basic InputStreamOutputStream Example

The following example uses the FileInputStream and the FileOutputStream class to read from a specified file and copies the content of this file to another file. import java.io.; class CopyFile { void copyString input, String output { FileInputStream inputStr; FileOutputStream outputStr; int data; try { inputStr = new FileInputStreaminput; outputStr = new FileOutputStreamoutput; while data = inputStr.read = -1 { outputStr.writedata; } inputStr.close; outputStr.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; } } Passing tempo.txt and tempo2.txt as arguments, heres a sample run of this code: Figure 12.3: Sample output for CopyFile Introduction to Programming II Page 173 J.E.D.I.

12.11 Modified InputStreamOutputStream Example

The next example is uses the PushbackInputStream class that decorates a FileInputStream object and the PrintStream class. import java.io.; class CopyFile { void copyString input { PushbackInputStream inputStr; PrintStream outputStr; int data; try { inputStr = new PushbackInputStreamnew FileInputStreaminput; outputStr = new PrintStreamSystem.out; while data = inputStr.read = -1 { outputStr.printlnread data: + char data; inputStr.unreaddata; data = inputStr.read; outputStr.printlnunread data: + char data; } inputStr.close; outputStr.close; } catch IOException ie { ie.printStackTrace; } } public static void mainString args[] { String inputFile = args[0]; CopyFile cf = new CopyFile; cf.copyinputFile; } } Test this code on a file containing a few lines or characters. Say, we have a file named tempo.txt containing the following text: one 1 two Passing tempo.txt to the code generates the following output: read data: o unread data: o read data: n unread data: n read data: e unread data: e read data: unread data: read data: 1 unread data: 1 read data: unread data: read data: Introduction to Programming II Page 174 J.E.D.I. unread data: read data: t unread data: t read data: w unread data: w read data: o unread data: o Introduction to Programming II Page 175 J.E.D.I.

12.12 Serialization