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
?
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With