lisak
lisak

Reputation: 21981

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

Upvotes: 7

Views: 21973

Answers (2)

Leonel
Leonel

Reputation: 29217

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.

Upvotes: 13

thkala
thkala

Reputation: 86403

A couple of alternatives:

  • ByteArrayInputStreams and several other similar classes are by definition non-blocking, as the data is already in the VM memory. In those cases the available() from InputStream could be what you need. This will not work when reading from an input source external to the program, e.g. a network socket, the standard input or perhaps even a file.

  • If the markSupported() method returns true for a specific InputStream instance, you may be able to use the mark() and reset() methods to return to the start of the stream after attempting to use read() on it.

EDIT:

By the way, ByteArrayInputStreams support mark() and reset() quite nicely and they are by default marked at position 0. This code:

InputStream x = new ByteArrayInputStream(new String("1234567890").getBytes());

byte b[] = new byte[1];

x.read(b, 0 , 1);
System.out.println(b[0]);

x.read(b, 0 , 1);
System.out.println(b[0]);

x.reset();

x.read(b, 0 , 1);
System.out.println(b[0]);

has this output:

49
50
49

Upvotes: 6

Related Questions