O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required