Languages
[Edit]
EN

Java - read from a InputStream with timeout

9 points
Created by:
Kourtney-White
635

In this short article, we would like to show a simple way how we can set timeout for each read operation in InputStream class in Java.

Simple answer:

If object that provides input stream doesn't support timeout parameter it is necessary to override read() method adding timeout logic.

 

Practical example

Edit

In this section you can find reusable TimeoutInputStream class that can be used when object that provides input stream doesn't support timeout parameter.

Example Program.java file:

 

Example TimeoutInputStream.java file:

Note: InputStream read(byte[] buffer) methods family doesn't throw IOException, they just returns number of read bytes even error occurred inside.

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join