"Merhaba Amigo! Bugün yeni bir şeyi nasıl yapacağınızı öğreneceksiniz: System.out nesnesini değiştirin."
System.out , System sınıfında çağrılan statik bir PrintStream değişkenidir . Bu değişken son değiştiriciye sahiptir, bu yüzden ona yeni bir değer atamanız yeterlidir. Ancak, System sınıfının bunu yapmak için özel bir yöntemi vardır: setOut(PrintStream stream) . Ve bunu kullanacağız.

"İlginç. Peki onu neyle değiştireceğiz?"

"Çıktı verilerini toplayabilecek bir nesneye ihtiyacımız var. ByteArrayOutputStream bu iş için en uygunudur. Bu, dinamik (yeniden boyutlandırılabilir) bir dizi olan ve OutputStream arabirimini uygulayan özel bir sınıftır."

"Bir dizi ile OutputStream arasında bir bağdaştırıcı mı?"

"Onun gibi bir şey. Kodumuz şöyle görünüyor."

kod
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!");
}

"Peki bu çizgiyi ne yapacağız?"

"Pekala, ne istersek. Örneğin, tersine çeviririz. O zaman kod şöyle görünür:"

kod
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!");
}

"Ne kadar ilginç! Şimdi bu küçük sınıfların sağladığı harika yetenekleri biraz anlamaya başlıyorum."
"İlginç ders için teşekkürler, Bilaabo."