Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent an empty InputStream

I'm reducing a stream of InputStreams like so:

InputStream total = input.collect(
    Collectors.reducing(
        empty,
        Item::getInputStream, 
        (is1, is2) -> new SequenceInputStream(is1, is2)));

For the identity InputStream, I'm using:

InputStream empty = new ByteArrayInputStream(new byte[0]);

This works, but is there a better way to represent an empty InputStream?

like image 206
ataylor Avatar asked Mar 13 '18 19:03

ataylor


People also ask

Can InputStream be null?

No, you can't. InputStream is designed to work with remote resources, so you can't know if it's there until you actually read from it.

What happens if InputStream is not closed?

The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more. I am talking about an InputStream in general.

How do you know if InputStream is closed?

There's no API for determining whether a stream has been closed. Applications should be (and generally are) designed so it isn't necessary to track the state of a stream explicitly. Streams should be opened and reliably closed in an ARM block, and inside the block, it should be safe to assume that the stream is open.


2 Answers

Since InputStream has only one abstract method, read(),

public abstract int read() throws IOException

Returns:
the next byte of data, or -1 if the end of the stream is reached.

it is easy to create an empty stream by an anonymous subclass. Like this:

InputStream empty = new InputStream() {
    @Override
    public int read() {
        return -1;  // end of stream
    }
};

But admittedly, it is more code than your empty ByteArrayInputStream.

like image 108
Thomas Fritsch Avatar answered Oct 04 '22 10:10

Thomas Fritsch


Since Java 11, you could use a static method InputStream.nullInputStream():

Returns a new InputStream that reads no bytes. The returned stream is initially open. The stream is closed by calling the close() method. Subsequent calls to close() have no effect.

like image 33
leventov Avatar answered Oct 04 '22 11:10

leventov