This question could be better rephrased as: How do you detect EOF in InputStream without blocking
I have a java program that is able to take input from System.in directly (without using a Scanner), I can also pipe input into the java program directly just like any program. However, when I pipe input into the program, the program keeps running. The idea is to stop the program if input was piped into it, but keep it running if we are waiting for user input.
My question is how do I use an InputStream to detect when the pipe is over (and end the program)? If I was using a Scanner I understand that I would be able to use Scanner#hasNext() to detect if I can read more however, I would like to do this just with an InputStream if possible.
My code currently looks something similar to this:
final InputStream in = System.in; // sometimes in won't be System.in
final byte[] buffer = new byte[1024];
while(true){
int len;
// the reason I use in.available() is so I only read if in.read() won't block
while(in.available() > 0 && (len = in.read(buffer)) > -1){
String s = new String(buffer, 0, len);
// do something with string
}
// sometimes do other stuff not relevant to this question
}
I am open to simpler solutions. The reason I am not using a Scanner object is because I need to read individual chars at a time, not just lines at a time. The purpose of this program isn't only input from the user, most of the time the input isn't even from System.in, I just included System.in in the above example because it will sometimes be System.in
EDIT: For whatever reason, I've dedicated about 2 hours of my life searching the internet for a simple solution for this. I've tried just using an InputStream, and even converted my code to use a ReadableByteChannel (created using Channels.newChannel()) to see if that would work. Every implementation I could find for something that wraps an InputStream is blocking. I guess the only way to fix this is to use another thread. Good luck future viewers.