繁体   English   中英

Java:如何在不阻塞的情况下测试InputStream上的EOF?

[英]Java: How to test for EOF on an InputStream without blocking?

我想做这样的事情:

// Implement an interruptible read
for(;;) {
  if (input.available() > 0)
    buffer.append(input.read());
  else if (input.eof())
    return buffer;
  else
    Thread.sleep(250);
}

如果我不关心阻塞,我会这样做:

for(;;) {
  c = input.read();
  if (c != -1)
    buffer.append(c);
  return buffer;
}

但我确实在乎,所以我需要使用available(),那么如何确定EOF呢?

您总是可以使用NIO库,因为它提供了非阻塞IO(顾名思义)。 有一篇关于IO vs NIO的Oracle博客文章: 在这里

另外,还提供了一些代码示例,其中包括InputStream读取时设置超时参数

如果您担心不阻塞,您可能会对套接字通道感兴趣。 可以在java.nio包中找到通道。 具体来说,您可能对ReadableByteChannel接口以及实现它的类感兴趣。

你会使用像这样的频道。

SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8000));

ByteBuffer buffer = ByteBuffer.allocate(1024);

while(channel.read(buffer) != -1) { 
// if -1 is returned then stream has been closed and loop should exit
    if (buffer.remaining() == 0) {
        // buffer is full, you might want to consume some of the data in buffer
        // or allocate a larger buffer before continuing
    }
    // we have now just read as much was available on the socket channel. Any
    // immediate  attempts to read from the channel again will result in the 
    // read method returning immediately.
    // Hence try to do something useful with the data before reading again
}

// channel is now closed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM