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:JAVAioexamples3> 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.

Basic I/O

Introducing I/O

Output Streams

Input Streams

Data Sources

File Streams

Network Streams

Filter Streams

Filter Streams

Print Streams

Data Streams

Streams in Memory

Compressing Streams

JAR Archives

Cryptographic Streams

Object Serialization

New I/O

Buffers

Channels

Nonblocking I/O

The File System

Working with Files

File Dialogs and Choosers

Text

Character Sets and Unicode

Readers and Writers

Formatted I/O with java.text

Devices

The Java Communications API

USB

The J2ME Generic Connection Framework

Bluetooth

Character Sets



Java I/O
Java I/O
ISBN: 0596527500
EAN: 2147483647
Year: 2004
Pages: 244

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net