"Szia, Amigo! Ma meg fogsz tanulni valami újat csinálni: cseréld le a System.out objektumot."
A System.out egy statikus PrintStream változó a System osztályban . Ez a változó rendelkezik a végső módosítóval, így egyszerűen hozzá kell rendelni egy új értéket. A System osztálynak azonban van egy speciális módszere erre: setOut(PrintStream stream) . És ezt fogjuk használni.
"Érdekes. És mivel fogjuk helyettesíteni?"
"Szükségünk van valami objektumra, amely össze tudja gyűjteni a kimeneti adatokat. A ByteArrayOutputStream a legalkalmasabb erre a feladatra. Ez egy speciális osztály, amely egy dinamikus (átméretezhető) tömb, és megvalósítja az OutputStream interfészt."
"Adapter egy tömb és az OutputStream között?"
"Valami ilyesmi. Így néz ki a kódunk."
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!");
}
– És mit kezdünk ezzel a vonallal?
"Nos, amit akarunk. Például megfordítanánk. Akkor a kód így nézne ki:"
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!");
}
"Milyen érdekes! Most kezdem egy kicsit megérteni azokat a nagyszerű képességeket, amelyeket ezek a kis osztályok nyújtanak."
– Köszönöm az érdekes leckét, Bilaabo.
GO TO FULL VERSION