“你好,阿米戈!今天你將學習如何做一些新的事情:替換 System.out 對象。”
System.out是在System類中調用的靜態PrintStream變量。該變量具有final修飾符,因此您只需為其分配一個新值即可。但是,System 類有一個特殊的方法來執行此操作:setOut(PrintStream stream)。這就是我們將要使用的。

“有趣。我們將用什麼來代替它?”

“我們需要一些可以收集輸出數據的對象。ByteArrayOutputStream最適合這項工作。這是一個特殊的類,它是一個動態(可調整大小的)數組並實現了 OutputStream 接口。”

“數組和 OutputStream 之間的適配器?”

“類似的東西。這是我們的代碼的樣子。”

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

“多麼有趣!現在我開始了解這些小班級提供的強大功能了。”
“謝謝你的有趣教訓,Bilaabo。”