how do you guys test for an empty InputStream? I know that InputStream is designed to work with remote resources, so you can't know if it's there until you actually read from it. I cannot use read() because current position would change and using mark() and resetting for that seems to be inappropriate.
The problem is, that sometimes one can't test if read() returns -1, because if you have a stream and some third party library uses it, you need to test if it is empty before you send it there.
By empty InputStreams I mean these new ByteArrayInputStream(new byte[0])
IntStream empty () is a method in java.util.stream.IntStream. This method returns an empty sequential IntStream. static <T> Stream<T> empty () Where, T is the type of stream elements, and the function returns an empty sequential stream. Example 1 : Creating empty IntStream. Example 2 : Creating empty LongStream.
It represents input stream of bytes. Applications that are defining subclass of InputStream must provide method, returning the next byte of input. A reset () method is invoked which re-positions the stream to the recently marked position.
I want to know if an InputStream is empty, but without using the method read (). Is there a way to know if it's empty without reading from it? Show activity on this post. 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.
FileInputStream: It is a subclass of InputStream. read() method: read() method returns a int which contains byte value of byte read. InputStream has 2 more read() methods which can return byte array. int read(byte[]) int read(byte[], int offset, int length) End Of Stream: When it reaches end of stream, read() method will return -1.
You can wrap your InputStream in a PushbackInputStream. This class will store the first few bytes from read()
in an internal buffer. You can later unread()
the bytes and pass the object to the 3rd party library.
I don't really like ByteArrayInputStream, because it keeps all the data from the stream in memory.
Also, in any case, you will be forced to read() to check for the empty stream, which means you'll hit the network, at least for a few bytes.
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