How can I check if an InputStream is empty without reading from it?

前端 未结 8 955
无人及你
无人及你 2020-12-08 18:10

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?

8条回答
  •  醉酒成梦
    2020-12-08 18:59

    If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

    input.mark(1);
    final int bytesRead = input.read(new byte[1]);
    input.reset();
    if (bytesRead != -1) {
        //stream not empty
    } else {
        //stream empty
    } 
    

    If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

提交回复
热议问题