I am using the code below to read a sql statement from stdin on the command line:
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
String line = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
while((line = in.readLine()) != null) {
sb.append(line);
}
} finally {
if (in!=null) in.close();
}
My problem is that the application needs to run sometimes with data from stdin, and sometimes not (no piped input). If there is no input in the above code, in.readLine() blocks. Is there a way to rewrite this code so that it can still run if nothing is piped in?
UPDATE: The application is designed to expect piped data from the command line, not from the keyboard.
I don’t think there is any way to check if you will eventually get another line of input. Note that your current code does terminate if the user closes the input stream (e.g., with ^D in a terminal).
BufferedReader.ready()checks if there is some data on the stream. Like T.J. mentioned, you might be unlucky and ask for data right before you actually receive it, and your user will be sad because you didn’t answer their query.Scanner.hasNextLine()is a blocking operation, so probably not what you’re looking for.You could have the user specify whether or not to read from System.in, for instance by using command line arguments.