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?

5
  • See stackoverflow.com/questions/1403772/… - the short answer appears to be "no"... Commented Sep 5, 2012 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)? Commented Sep 5, 2012 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. Commented Sep 5, 2012 at 17:49
  • @TomSeddon - Actually, that question seems to give "yes" answer - System.console() works for me at the moment :) Commented Sep 5, 2012 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. Commented Sep 5, 2012 at 18:10

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.