73

我想知道 anInputStream是否为空,但不使用方法read()。有没有办法在不读取它的情况下知道它是否为空?

4

8 回答 8

67

不,你不能。InputStream旨在与远程资源一起使用,因此在您实际读取它之前您无法知道它是否存在。

但是,您可以使用 a java.io.PushbackInputStream,它允许您从流中读取以查看那里是否有东西,然后将其“推回”流(这不是它真正的工作方式,但这就是它的行为方式客户端代码)。

于 2009-10-06T08:36:30.003 回答
57

我想你正在寻找inputstream.available(). 它不会告诉你它是否为空,但它可以告诉你是否有数据可供读取。

于 2009-10-06T08:35:47.040 回答
10

根据使用 PushbackInputStream 的建议,您将在此处找到一个示例实现:

/**
 * @author Lorber Sebastien <i>(lorber.sebastien@gmail.com)</i>
 */
public class NonEmptyInputStream extends FilterInputStream {

  /**
   * Once this stream has been created, do not consume the original InputStream 
   * because there will be one missing byte...
   * @param originalInputStream
   * @throws IOException
   * @throws EmptyInputStreamException
   */
  public NonEmptyInputStream(InputStream originalInputStream) throws IOException, EmptyInputStreamException {
    super( checkStreamIsNotEmpty(originalInputStream) );
  }


  /**
   * Permits to check the InputStream is empty or not
   * Please note that only the returned InputStream must be consummed.
   *
   * see:
   * http://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it
   *
   * @param inputStream
   * @return
   */
  private static InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException, EmptyInputStreamException {
    Preconditions.checkArgument(inputStream != null,"The InputStream is mandatory");
    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if ( b == -1 ) {
      throw new EmptyInputStreamException("No byte can be read from stream " + inputStream);
    }
    pushbackInputStream.unread(b);
    return pushbackInputStream;
  }

  public static class EmptyInputStreamException extends RuntimeException {
    public EmptyInputStreamException(String message) {
      super(message);
    }
  }

}

这里有一些通过测试:

  @Test(expected = EmptyInputStreamException.class)
  public void test_check_empty_input_stream_raises_exception_for_empty_stream() throws IOException {
    InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
    new NonEmptyInputStream(emptyStream);
  }

  @Test
  public void test_check_empty_input_stream_ok_for_non_empty_stream_and_returned_stream_can_be_consummed_fully() throws IOException {
    String streamContent = "HELLooooô wörld";
    InputStream inputStream = IOUtils.toInputStream(streamContent, StandardCharsets.UTF_8);
    inputStream = new NonEmptyInputStream(inputStream);
    assertThat(IOUtils.toString(inputStream,StandardCharsets.UTF_8)).isEqualTo(streamContent);
  }
于 2013-10-02T13:20:21.063 回答
7

如果InputStream您使用的支持标记/重置支持,您还可以尝试读取流的第一个字节,然后将其重置为原始位置:

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

如果您不控制InputStream使用哪种类型,则可以使用该markSupported()方法检查标记/重置是否适用于流,否则回退到该available()方法或该java.io.PushbackInputStream方法。

于 2009-10-06T17:22:22.100 回答
5

您可以使用该方法询问流在您调用它时available()是否有可用的数据。但是,不能保证该函数适用于所有类型的输入流。这意味着您不能使用来确定调用是否会实际阻塞。available()read()

于 2009-10-06T08:39:37.640 回答
2

如何使用inputStreamReader.ready()找出答案?

import java.io.InputStreamReader;

/// ...

InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
    // do something
}

// ...
于 2009-10-07T05:25:59.473 回答
0

不读书是做不到的。但是您可以使用如下解决方法。

您可以使用mark()reset()方法来执行此操作。

mark(int readlimit) 方法标记此输入流中的当前位置。

reset() 方法将此流重新定位到最后一次在此输入流上调用标记方法时的位置。

在您可以使用标记和重置之前,您需要测试您正在读取的输入流是否支持这些操作。您可以使用 markSupported 来做到这一点。

mark 方法接受一个限制(整数),它表示要提前读取的最大字节数。如果您阅读超过此限制,则无法返回此标记。

要将此功能应用于此用例,我们需要将位置标记为 0,然后读取输入流。在我们需要重置输入流之后,输入流将恢复为原始流。

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

这里如果输入流为空,则 read() 方法将返回 -1。

于 2020-04-19T18:03:38.913 回答
-4
public void run() {
    byte[] buffer = new byte[256];  
    int bytes;                      

    while (true) {
        try {
            bytes = mmInStream.read(buffer);
            mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}
于 2015-05-01T11:28:37.333 回答