[ACCEPTED]-Custom implementation of InputStream-java-io

Accepted answer
Score: 12

You only nead to implement the read() method without parameters. All other methods 4 are implemented as calls to that method. For 3 performance reasons (and even ease of implementation) it 2 might be easier to implement the three-argument read() method instead and re-implement 1 the no-args read() method in terms of that method.

Score: 9

Some very important points which I met when 20 implementing my InputStream.

  1. Override available(). As 19 the Javadoc says:

    The available method for 18 class InputStream always returns 0. This 17 method should be overridden by subclasses.

    not 16 overriding this method will causes that 15 any tempt to test whether this stream is 14 readable return false. For example, if you feed your 13 inputStream to a inputStreamReader, this reader will always return false when you invoke 12 reader.ready().

  2. return -1 in the read(). The doc didn't emphasize 11 it:

    If no byte is available because the end 10 of the stream has been reached, the value 9 -1 is returned. This method blocks until 8 input data is available, the end of the 7 stream is detected, or an exception is thrown.

    if 6 you choose to block read() when no data is available, you 5 have to remember to return -1 at some situations. Not 4 doing this may causes that another read(byte b[], int off, int len) blocks 3 for the following code in the source:

    for (; i < len ; i++) {// default len is a relative large number (8192 - readPosition)
        c = read();
        if (c == -1) {
        b[off + i] = (byte)c;

    And 2 this causes some(if not all) high level 1 read block, like a reader's readLine(), read() etc.

Score: 4

For possibly large data you can use com.google.common.io.FileBackedOutputStream from 1 guava.

Javadoc: An OutputStream that starts buffering to a byte array, but switches to file buffering once the data reaches a configurable size.

Using out.getSupplier().getInput() you get your InputStream.

Score: 1

There's absolutely no need to create a custom 7 InputStream. Use ByteArrayInputStream, something like this:

public static InputStream createStream(){
    final String csv = createCsvFromDataBaseValues();
    return new ByteArrayInputStream(csv.getBytes());

Especially given 6 this quote:

My idea is to load all the data 5 in the constructor and then override the 4 read method.

If you do it like this, you 3 gain absolutely nothing by implementing 2 a custom InputStream. It's pretty much equivalent to 1 the approach I outlined above.

Score: 1

Why do you need a custon inputstream? why 3 not just write the csv data as you generate 2 it to the outputstream being written to 1 the ftp server?

Score: 0

If the data is not too large, you could:

  • Read it all
  • Convert to CSV (text)
  • Get the text bytes (via String.getBytes(encoding))
  • But the byte array in a ByteArrayInputStream


More Related questions