Random input stream : InputStream « File Input Output « Java

Random input stream

 * Copyright WizTools.org
 * Licensed under the Apache License, Version 2.0:
 * http://www.apache.org/licenses/LICENSE-2.0
//package org.wiztools.commons;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

 * Originally written by Elliotte Rusty Harold for the book Java I/O 2nd edition.
 * @author subwiz
public class RandomInputStream extends InputStream {

    private Random generator = new Random();
    private boolean closed = false;

    public int read() throws IOException {
        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];
        System.arraycopy(temp, 0, data, offset, length);
        return length;


    public int read(byte[] data) throws IOException {
        return data.length;


    public long skip(long bytesToSkip) throws IOException {
        // 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;


Related examples in the same category

1.Creating an input or output stream on a ByteBuffer
2.Creating a Manifest for a JAR File
3.Convert InputStream to String
4.An limited-data-size input stream
5.An input stream which reads sequentially from multiple sources
6.Combined InputStream
7.Size Limit InputStream
8.Minimal InputStream subclass to fetch bytes form a String
9.Read and return the entire contents of the supplied InputStream. This method always closes the stream when finished reading.
10.Compare two InputStream
11.Read and return the entire contents of the supplied InputStream.
12.Deserializes an object from an input stream.
13.Reads at most certain bytes from input stream and returns them as a byte array.
14.Convert Reader to InputStream
15.A trace of the data that is being retrieved from an input stream
16.EOLConvertingInputStream: InputStream which converts \r bytes not followed by \n and \n not preceded by \r to \r\n.
17.A line reading wrapper that works with byte streams.
18.Smart Encoding InputStream
19.Wraps a stream that has been exported to import the data in readable form
20.This input stream wrapper closes the base input stream when fully read.
21.LZFInputStream and LZFOutputStream