Reading from an InputStream with a Timeout
Is it possible to read from an InputStream and specify a timeout? Yes, but it's not as straightforward as it may seem. The InputStream.read() method may be non-interruptible, and the InputStream.available() method may return 0 even when data is available.
Facts Supported by Sun's Documentation
Using InputStream.available()
InputStream.available() should return an estimate of the number of bytes available to read without blocking, but it's important to note that subclasses are responsible for overriding this method. In practice, concrete input stream classes do provide meaningful values for available().
Caveats
Simplest Solution (No Blocking)
byte[] inputData = new byte[1024]; int result = is.read(inputData, 0, is.available());
Richer Solution (Maximizes Buffer Fill Within Timeout)
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis) throws IOException { int bufferOffset = 0; long maxTimeMillis = System.currentTimeMillis() + timeoutMillis; while (System.currentTimeMillis() < maxTimeMillis & bufferOffset < b.length) { int readLength = java.lang.Math.min(is.available(), b.length - bufferOffset); int readResult = is.read(b, bufferOffset, readLength); if (readResult == -1) break; bufferOffset += readResult; } return bufferOffset; }
The above is the detailed content of How Can I Read from a Java InputStream with a Timeout?. For more information, please follow other related articles on the PHP Chinese website!