5

For example, when I'm writing program that outputs text to stdout and uses colors (via escape sequences), I would like to disable those colors if output goes to other program (like less, grep) or to file, since color codes mess up the output.

Is it possible to do it from Java process?

Rogach
  • 26,050
  • 21
  • 93
  • 172
  • See http://stackoverflow.com/questions/1403772/how-can-i-check-if-a-java-programs-input-output-streams-are-connected-to-a-term - the short answer appears to be "no"... – Tom Seddon Sep 05 '12 at 16:34
  • 1
    Why not provide an argument that can be passed on the command line to invoke plain text mode (or to enable color mode depending on which mode is used more often)? – Sticks Sep 05 '12 at 16:59
  • @Sticks - Well, it could be possible - but is well too obvious to ask this question if that would be an acceptable solution :) Digging through tens of options just to get to that option is not good, so I wanted to get some automatic way to do it. – Rogach Sep 05 '12 at 17:49
  • @TomSeddon - Actually, that question seems to give "yes" answer - System.console() works for me at the moment :) – Rogach Sep 05 '12 at 17:54
  • 1
    @Rogach You might want to describe how you've solved the problem using System.console() as an answer to your own question to help future readers who would face the same problem. – Dušan Rychnovský Sep 05 '12 at 18:10

1 Answers1

5

I solved it in a following way (described here):

System.console() will return Console object, if there is some terminal connected to application, and it will return null if you pipe output into other app or save it to file.

Thus it becomes a simple check:

if (System.console() == null) {
  // ... no console, print dull plaintext
} else {
  // we have a console, now we can output colors as well
}

(tested on Linux Mint 10)

Community
  • 1
  • 1
Rogach
  • 26,050
  • 21
  • 93
  • 172