An Efficient Stream Copier
As a useful example of both input and output streams, in Example 3-3, I'll present a StreamCopier class that copies data between two streams as quickly as possible. (I'll reuse this class in later chapters.) This method reads from the input stream and writes onto the output stream until the input stream is exhausted. A 1K buffer is used to try to make the reads efficient. A main( ) method provides a simple test for this class by reading from System.in and copying to System.out.
Example 3-3. The StreamCopier class
package com.elharo.io; import java.io.*; public class StreamCopier { public static void main(String[] args) { try { copy(System.in, System.out); } catch (IOException ex) { System.err.println(ex); } } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } |
Here's a simple test run:
D:JAVAioexamples 3> java com.elharo.io.StreamCopier this is a test this is a test 0987654321 0987654321 ^Z
Input was not fed from the console (DOS prompt) to the StreamCopier program until the end of each line. Since I ran this on Windows, the end-of-stream character is Ctrl-Z. On Unix, it would have been Ctrl-D.