If a program sends data to my standard input stream in Java through a pipe, how can I make my Java program atuomatically detect if new data is coming through the pipe into the input stream so that I can read it?
I know that I could use an infinite while loop that constantly keeps reading and checking the standard input stream. But this is inefficent and it takes a lot of resources. I am not even allowed to do this for my assignment.
It has to be synchronized somehow. Can I put a listener on the pipe or standard input that says: "Hey! Read the standard input now! New data is coming!" or can I make the pipe send interrupts or how do I do this?
As others have said, there is no way to check to see if input is available from an InputStream
(or Reader
) that doesn't either block the current thread ... or involve expensive polling.
The simple solution is just to attempt the read, and block until data arrives. This solution is OK unless ...
In such cases, you either need to use NIO selectors (which allow you to wait until data arrives on one of a set of streams, or use a different thread for reading the data from each stream, and other threads for processing it (or doing other things). In the latter case, you probably need some kind of queueing mechanism to pass "messages" from the reader thread / threads to the processing thread / threads.
However, the bottom line is that we can't offer a good concrete solution without more details of your application.
One piece of advice: don't try to use the InputStream.available()
or Reader.ready()
. These involve polling ... and their specified semantics are such that that can't tell you definitively if a read
will block. They are basically useless ...
The standard way to do this is to use the read
method on the inputstream?
If the data is text then you may use the readLine
method.
See this informative link
Of course, the tread that is calling this code will block, so it would ideally this code would be in a different thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With