Home >Java >javaTutorial >How Can I Read from a Java InputStream with a Timeout?

How Can I Read from a Java InputStream with a Timeout?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 22:12:10220browse

How Can I Read from a Java InputStream with a Timeout?

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

  1. InputStream.read() can be non-interruptible.
  2. Using a Reader or InterruptibleChannel won't help.
  3. InputStream.available() can always return 0.
  4. InputStream.close() can block or do nothing.
  5. There is no general way to kill another thread.

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

  1. Ensure you use carriage-return when typing input in Windows.
  2. InputStream.available() will return 0 until data is available from the shell.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn