http : // www . adjective . org /

Uniform

Example : A Common IO Interface

Description

java.io.InputStream and java.io.Reader both have a read method that takes no arguments, and returns an int. However, there is no shared interface between them, so it is no possible to write a single method that can read from either type of object.

NB: It is intentional (and fairly important) that InputStream and Reader do not share a common interface - the return value from InputStream.read() is a byte and the return value from Reader.read() is a char. When dealing with plain ASCII text, a char is a byte, but unicode has multibyte characters, so the InputStream would only read half a character. Please consider this example to be a demonstration only - it is unlikely to be useful in practice.

Also, these example read from the InputStream and Reader one byte (or character) at a time. This is quite inefficient, and is done for demonstration purposes only.

Code

public interface Readable {
  public int read() throws IOException;
}
public char[] readAll(Readable readable) throws IOException {
  CharArrayWriter writer = new CharArrayWriter();
  for (;;) {
    int read = readable.read();
    if (read == -1) break;
    else            writer.write(read);
  }
  return writer.toCharArray();
}

public char[] readAll(InputStream stream) throws IOException {
  Uniform uniform = new Uniform(stream);
  Readable readable = (Readable) uniform.as(Readable.class);
  return readAll(readable);
}

public char[] readAll(Reader reader) throws IOException {
  Uniform uniform = new Uniform(reader);
  Readable readable = (Readable) uniform.as(Readable.class);
  return readAll(readable);
}

Samples

This example is available in the org.adjective.uniform.sample.input package, in the source/java/sample directory.