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. Furthermore, they may want to override methods that perform functions like 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.macfaq.io;

import java.util.*;
import java.io.*;

public class RandomInputStream extends InputStream {

  private transient Random generator = new Random();

  public int read() {

    int result = generator.nextInt() % 256;
    if (result < 0) result = -result;
    return result;

  }

  public int read(byte[] data, int offset, int length) throws IOException {

    byte[] temp = new byte[length];
    generator.nextBytes(temp);
    System.arraycopy(temp, 0, data, offset, length);
    return length;

  }

  public int read(byte[] data) throws IOException {

    generator.nextBytes(data);
    return data.length;

  }

  public long skip(long bytesToSkip) throws IOException {
  
    // It's all random so skipping has no effect.
    return bytesToSkip;
  
  }
}

The no-argument read() ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.