3 ms·
I haven’t figured out a way to do this in native Java, so I end up wrapping my Java CLI tools in a bash wrapper (as a self executing JAR). This wrapper’s main p
by mbreese 7y ago
I haven’t figured out a way to do this in native Java, so I end up wrapping my Java CLI tools in a bash wrapper (as a self executing JAR). This wrapper’s main purpose is to set a Java property based on the results of the bash test:
if [ -t 0 ]; then
fi
I then use this flag to know if I should do things like export CLI progress bars or other interactive things.
- tedunangst 7y agoAllegedly System.console() but of course it's not actually the same and can be wrong in some important cases, leaving you with jni.
- marvy 7y agowhen would console() be wrong?
- skissane 7y agoSee this code: https://github.com/openjdk/jdk/blob/39c023612dbdd1016ad24b60fdef464bf21d1016/src/java.base/unix/native/libjava/Console_md.c#L38 https://github.com/openjdk/jdk/blob/39c023612dbdd1016ad24b60... It only works when isatty() returns true on both stdin and stdout. If you redirect stdin from a file, but stdout still goes to tty, isatty() on stdout will return true, but System.console() will return null. If you are using isatty() on stdout to decide whether to display fancy output, then whether stdin is a tty or not isn't relevant. So in that scenario System.console() doesn't do what you want.
- marvy 7y agoThat makes sense, thanks! So it's a bit over-cautious.
- skissane 7y agoYou can call isatty() using a Java FFI library such as JNA or JNR. Some day, Java will come with this out-of-the-box and an external library will not be needed – see https://openjdk.java.net/jeps/191 https://openjdk.java.net/jeps/191 For JNA (probably JNR too, my personal experience is only with JNA though), just have to add the JAR to your project (or the Maven/Gradle dependency). The JAR includes native libraries for various platforms. It is non-portable, it won't work on Windows, although you may not care about that, and if you do, Windows has similar APIs (e.g. calling GetConsoleMode() on the file handle will fail if the handle doesn't point to a console.)
- tyingq 7y agoJansi might be worth a look. Provides isatty() and other things that might be helpful for a Java command line app. Works on Windows also. https://github.com/fusesource/jansi https://github.com/fusesource/jansi
- the8472 7y agolinux-specific hack: read /proc/self/fdinfo/1 and check if its mnt_id (/proc/self/mountinfo) corresponds to a devpts mount.