"హలో, అమిగో! ఈరోజు మీరు కొత్తది ఎలా చేయాలో నేర్చుకోబోతున్నారు: 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!");
}
"ఎంత ఆసక్తికరంగా ఉంది! ఇప్పుడు నేను ఈ చిన్న తరగతులు అందించే గొప్ప సామర్థ్యాలను కొంచెం అర్థం చేసుకోవడం ప్రారంభించాను."
"ఆసక్తికరమైన పాఠానికి ధన్యవాదాలు, బిలాబో."
GO TO FULL VERSION