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

前端 未结 8 872
无人及你
无人及你 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 19:01

    Without reading you can't do this. But you can use a work around like below.

    You can use mark() and reset() methods to do this.

    mark(int readlimit) method marks the current position in this input stream.

    reset() method repositions this stream to the position at the time the mark method was last called on this input stream.

    Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.

    The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.

    To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.

        if (inputStream.markSupported()) {
              inputStream.mark(0);
              if (inputStream.read() != -1) {
                   inputStream.reset();
              } else {
                   //Inputstream is empty
              }
        }
    

    Here if the input stream is empty then read() method will return -1.

    0 讨论(0)
  • 2020-12-08 19:03

    How about using inputStreamReader.ready() to find out?

    import java.io.InputStreamReader;
    
    /// ...
    
    InputStreamReader reader = new InputStreamReader(inputStream);
    if (reader.ready()) {
        // do something
    }
    
    // ...
    
    0 讨论(0)
提交回复
热议问题