Java: how to check EOF on an InputStream without blocking?

I want to do something like this:

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

If I did not care about the lock, I would do this:

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

But I don’t care, so I need to use accessible (), so how can I define EOF?

+4
source share
2 answers

Instead, you can always use the NIO library, as this provides a non-blocking IO (as the name suggests). There is an Oracle blog post about IO vs NIO: Here .

As an alternative, code examples are given here about setting timeout options when reading from an InputStream

+4
source

You may be interested in socket channels if you are not worried about blocking. Channels can be found in the java.nio package. In particular, you might be interested in the ReadableByteChannel interface and the classes that implement it.

You would use channels like this.

 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 
+1
source

Source: https://habr.com/ru/post/1383533/


All Articles