Subclassing InputStream

Immediate subclasses of InputStream must provide an implementation of the abstract read( ) method. They may also override some of the nonabstract methods. For example, the default markSupported( ) method returns false, mark( ) does nothing, and reset( ) tHRows an IOException. Any class that allows marking and resetting must override these three methods. Subclasses should also override available( ) to return something other than 0. Furthermore, they may override skip( ) and the other two read( ) methods to provide more efficient implementations.

Example 3-2 is a simple class called RandomInputStream that "reads" random bytes of data. This provides a useful source of unlimited data you can use in testing. A java.util.Random object provides the data.

Example 3-2. The RandomInputStream class

package com.elharo.io; import java.util.*; import java.io.*; public class RandomInputStream extends InputStream { private Random generator = new Random( ); private boolean closed = false; public int read( ) throws IOException { checkOpen( ); int result = generator.nextInt( ) % 256; if (result < 0) result = -result; return result; } public int read(byte[] data, int offset, int length) throws IOException { checkOpen( ); byte[] temp = new byte[length]; generator.nextBytes(temp); System.arraycopy(temp, 0, data, offset, length); return length; } public int read(byte[] data) throws IOException { checkOpen( ); generator.nextBytes(data); return data.length; } public long skip(long bytesToSkip) throws IOException { checkOpen( ); // It's all random so skipping has no effect. return bytesToSkip; } public void close( ) { this.closed = true; } private void checkOpen( ) throws IOException { if (closed) throw new IOException("Input stream closed"); } public int available( ) { // Limited only by available memory and the size of an array. return Integer.MAX_VALUE; } }

The no-argument read( ) method returns a random int in the range of an unsigned byte (0 to 255). The other two read( ) methods fill a specified part of an array with random bytes. They return the number of bytes read (in this case the number of bytes created).

Категории