Quick and dirty implementation of the Java’s InputStream, that can generate a desired number of random characters, without buffering it in memory. May be useful for unit testing.
import org.apache.commons.lang3.RandomStringUtils; import java.io.IOException; import java.io.InputStream; public class RandomCharsInputStream extends InputStream { private static final int ALPHABETIC = 1; private static final int ALPHANUMERIC = 2; private static final int ASCII = 3; private static final int NUMERIC = 4; private static final int CHARS = 5; private int type = ALPHABETIC; private long size = 0; private long charsRead = 0; private char[] chars; public static final RandomCharsInputStream newAlphabetic(long size) { return new RandomCharsInputStream(size, ALPHABETIC); } public static final RandomCharsInputStream newAlphanumeric(long size) { return new RandomCharsInputStream(size, ALPHANUMERIC); } public static final RandomCharsInputStream newAscii(long size) { return new RandomCharsInputStream(size, ASCII); } public static final RandomCharsInputStream newNumeric(long size) { return new RandomCharsInputStream(size, NUMERIC); } public static final RandomCharsInputStream newWithChars(long size, char... chars) { return new RandomCharsInputStream(size, chars); } public static final RandomCharsInputStream newWithChars(long size, String chars) { return new RandomCharsInputStream(size, chars.toCharArray()); } private RandomCharsInputStream(long size, int type) { this.size = size; this.type = type; } private RandomCharsInputStream(long size, char... chars) { this.size = size; this.type = CHARS; this.chars = chars; } @Override public int read() throws IOException { if (charsRead >= size) return -1; char c; switch (type) { case ALPHABETIC: c = RandomStringUtils.randomAlphabetic(1).charAt(0); break; case ALPHANUMERIC: c = RandomStringUtils.randomAlphanumeric(1).charAt(0); break; case ASCII: c = RandomStringUtils.randomAscii(1).charAt(0); break; case NUMERIC: c = RandomStringUtils.randomNumeric(1).charAt(0); break; case CHARS: c = RandomStringUtils.random(1, chars).charAt(0); break; default: throw new IllegalArgumentException("Unknown random type: " + type); } charsRead++; return c; } }
Usage examples:
RandomCharsInputStream in = RandomCharsInputStream.newAscii(10000); RandomCharsInputStream in = RandomCharsInputStream.newNumeric(100); RandomCharsInputStream in = RandomCharsInputStream.newWithChars(30, "xyz");