Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for empty InputStream in Java

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])

like image 448
lisak Avatar asked Mar 30 '11 22:03

lisak


People also ask

How to create an empty IntStream in Java?

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.

What is the use of InputStream in Java?

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.

How to know if an InputStream is empty without reading from it?

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.

What is the read () method of FileInputStream in Java?

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.


1 Answers

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.

like image 134
Leonel Avatar answered Sep 21 '22 21:09

Leonel