How can I check if a Java program's input/output streams are connected to a terminal?

Viewed 12377

I would like a Java program to have different default settings (verbosity, possibly colored output where supported) depending on its use. In C, there is an isatty() function which will return 1 if a file descriptor is connected to a terminal, and 0 otherwise. Is there an equivalent for this in Java? I haven't seen anything in the JavaDoc for InputStream or PrintStream.

6 Answers

If you don't want to compile C source yourself, you can use the Jansi library. It's a lot smaller than jnr-posix

<dependency>
  <groupId>org.fusesource.jansi</groupId>
  <artifactId>jansi</artifactId>
  <version>1.17.1</version>
</dependency>

...

import static org.fusesource.jansi.internal.CLibrary.isatty;

...

System.out.println( isatty(STDIN_FILENO) );

There is another way. I discovered this by chance as I needed to use /dev/tty. I noticed a FileSystemException is raised, when the Java program tries to create an InputStream from the tty device file if the program is not part of a TTY, like Gradle daemons. However if any of the stdin, stdout, or stderr is connected to a terminal, this code won't raise an exception with the message:

  • on macOS (Device not configured)
  • on Linux No such device or address

Unfortunately checking if /dev/tty exists and is readable will be true. This FSE only happens when actually trying to read from the file, without reading it.

// straw man check to identify if this is running in a terminal
// System.console() requires that both stdin and stdout are connected to a terminal
// which is not always the case (eg with pipes).
// However, it happens that trying to read from /dev/tty works
// when the application is connected to a terminal, and fails when not
// with the message
//     on macOS '(Device not configured)'
//     on Linux 'No such device or address'
//
// Unfortunately Files::notExists or Files::isReadable don't fail.
//noinspection EmptyTryBlock
try (var ignored = Files.newInputStream(Path.of("/dev/tty"))) {
  return "in a tty"
} catch (FileSystemException fileSystemException) {
  return "not in a tty";
}

While this approach is ugly, it avoids the use of third party libraries. This doesn't answer the question which of the standard stream is connected to a terminal though, for that it might me better to rely on a terminal library, like Jansi or JLine 3.

Related