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).
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