Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override (not the OOP override) the output of System.out.print()?

Tags:

java

Is there a way I can override the System.out.print()'s output?

Here is what I am trying to do:

System.out.print("A B C D E F G H I J K L");

Will print : A B C D E F G H I J K L

Now I want to write a method which overrides this output from a specific position. Something like,

override(7, "X Y Z");

Should output

A B C X Y Z G H I J K L 

These should happen right in the console.

like image 952
bragboy Avatar asked Feb 09 '10 05:02

bragboy


2 Answers

  1. create your own PrintStream - e.g. public class YourPrintStream extends PrinterStream.
  2. override the print(String s) method and change the string there any way you like. Then call super.print(s));
  3. Call System.setOut(new YourPrintStream())

Then everytime System.out.println is called, the passed string will be under your control before going into the actual stream.

like image 191
Bozho Avatar answered Nov 15 '22 13:11

Bozho


System.out is an output stream. Once you put something in, you can't go in after it and change it. Even if you could, it is just a byte representation at that point. The closest you're going to come is making the modification before you send the data to standard out, or wrapping the console such that you capture the data on the other side.

like image 39
danben Avatar answered Nov 15 '22 11:11

danben