If the input is interactive, i.e. from the console, I want to print a command prompt e.g. ">"
But if it is redirected e.g. from a file, then I do not want to prompt.
System.in is an abstract InputStream which does not appear to have any method for this.
Maybe you could use instanceof if the concrete type is different?
As well, if System.out is redirected to a file I also do not want to prompt
AFAIK, there is no way to do this in pure Java, and even doing it in JNI / JNA would be complicated.
An alternative might be to use the new Console API introduced in JDK 1.6. This allows you to try to get a reader/writer for the console. If it succeeds, the result is guaranteed to be interactive ... in the sense that you mean.
A second alternative would be to do the "check for interactivity" in the wrapper script that you use to launch your application, and pass the information to Java via the system properties. For instance, on a GNU/Linux system the tty(1)
command can be used to tell if stdin is a connected to a "tty" device.
Note that there are other ways to deal with a requirement to avoid unwanted prompts when running non-interactively:
If System.out is redirected to a file I also do not want to prompt.
(I think you might mean that System.in
is redirected. That is the normal way to non-interactively run an application that normally takes interactive input from the user ...)
The alternatives include:
You could modify the program to write the prompts to (say) System.err
and redirect that to a different place.
You could modify the program to have options that mean "don't prompt" or "take input from a file".
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