„Hallo Amigo! Heute wirst du etwas Neues lernen: wie du das System.out-Objekt ersetzt.“
System.out ist eine statische PrintStream-Variable namens out in der System-Klasse. Diese Variable hat den Modifikator final, also weist du ihr einfach einen neuen Wert zu. Die System-Klasse verfügt jedoch über eine spezielle Methode, um dies zu tun: setOut(PrintStream stream). Und genau das werden wir nutzen.

„Interessant. Und durch was werden wir sie ersetzen?“

„Wir brauchen ein Objekt, das die Ausgabedaten sammeln kann. ByteArrayOutputStream ist für diese Aufgabe bestens geeignet. Dies ist eine spezielle Klasse, die ein dynamisches (in seiner Größe veränderbares) Array ist und das OutputStream-Interface implementiert

„Ein Adapter zwischen einem Array und OutputStream?“

„Sowas in der Art. So sieht unser Code aus.“

Code
public static void main(String[] args) throws Exception
{
 //Save the current PrintStream in a special variable
 PrintStream consoleStream = System.out;

 //Create a dynamic array
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 //Create an adapter for the PrintStream class
 PrintStream stream = new PrintStream(outputStream);
 //Set it as the current System.out
 System.setOut(stream);

 //Call a function that knows nothing about our changes
 printSomething();

 //Convert the data written to our ByteArray into a string
 String result = outputStream.toString();

 //Put everything back to the way it was
 System.setOut(consoleStream);
}

public static void printSomething()
{
 System.out.println("Hi");
 System.out.println("My name is Amigo");
 System.out.println("Bye-bye!");
}

„Und was machen wir mit dieser Zeile?“

„Na, was immer wir wollen. Wir können sie zum Beispiel umkehren. Dann würde der Code wie folgt aussehen:“

Code
public static void main(String[] args) throws Exception
{
 //Save the current PrintStream in a special variable
 PrintStream consoleStream = System.out;

 //Create a dynamic array
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 //Create an adapter for the PrintStream class
 PrintStream stream = new PrintStream(outputStream);
 //Set it as the current System.out
 System.setOut(stream);

 //Call a function that knows nothing about our changes
 printSomething();

 //Convert the data written to our ByteArray into a string
 String result = outputStream.toString();

 //Put everything back to the way it was
 System.setOut(consoleStream);

 //Reverse the string
 StringBuilder stringBuilder = new StringBuilder(result);
 stringBuilder.reverse();
 String reverseString = stringBuilder.toString();

 //Output it to the console
 System.out.println(reverseString);
}

public static void printSomething()
{
 System.out.println("Hi");
 System.out.println("My name is Amigo");
 System.out.println("Bye-bye!");
}

„Sehr interessant! So langsam verstehe ich, welche großartigen Möglichkeiten diese kleinen Klassen bereithalten.“
„Danke für die interessante Lektion, Bilaabo.“