"हॅलो, अमिगो! आज तुम्ही काहीतरी नवीन कसे करायचे ते शिकणार आहात: System.out ऑब्जेक्ट बदला."
System.out हे स्टॅटिक प्रिंटस्ट्रीम व्हेरिएबल आहे जे सिस्टम क्लासमध्ये कॉल केले जाते . या व्हेरिएबलमध्ये अंतिम सुधारक आहे, म्हणून तुम्ही त्याला एक नवीन मूल्य नियुक्त करता. तथापि, सिस्टम क्लासमध्ये हे करण्यासाठी एक विशेष पद्धत आहे: setOut(PrintStream stream) . आणि तेच आपण वापरू.

"इंटरेस्टिंग. आणि आम्ही ते कशाने बदलू?"

"आम्हाला आउटपुट डेटा संकलित करू शकणार्‍या ऑब्जेक्टची आवश्यकता आहे. या कामासाठी ByteArrayOutputStream सर्वात योग्य आहे. हा एक विशेष वर्ग आहे जो डायनॅमिक (आकारात बदलता येण्याजोगा) अॅरे आहे आणि आउटपुटस्ट्रीम इंटरफेस लागू करतो."

"अॅरे आणि आउटपुटस्ट्रीम दरम्यान अॅडॉप्टर?"

"असंच काहीतरी. आमचा कोड कसा दिसतो ते इथे आहे."

कोड
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!");
}

"आणि या ओळीचे आपण काय करू?"

"ठीक आहे, आम्हाला जे हवे आहे. उदाहरणार्थ, आम्ही ते उलट करू. मग कोड असा दिसेल:"

कोड
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!");
}

"किती मनोरंजक! आता मला हे छोटे वर्ग प्रदान करणार्‍या महान क्षमतांबद्दल थोडेसे समजू लागले आहेत."
"रंजक धड्याबद्दल धन्यवाद, बिलाबो."