"Xin chào, Amigo! Hôm nay bạn sẽ học cách làm một việc mới: thay thế đối tượng System.out."
System.out là một biến PrintStream tĩnh được gọi ra trong lớp System . Biến này có công cụ sửa đổi cuối cùng , vì vậy bạn chỉ cần gán cho nó một giá trị mới. Tuy nhiên, lớp Hệ thống có một phương thức đặc biệt để thực hiện việc này: setOut(PrintStream stream) . Và đó là những gì chúng ta sẽ sử dụng.

"Thật thú vị. Và chúng ta sẽ thay thế nó bằng cái gì?"

"Chúng tôi cần một số đối tượng có thể thu thập dữ liệu đầu ra. ByteArrayOutputStream phù hợp nhất cho công việc này. Đây là một lớp đặc biệt là mảng động (có thể thay đổi kích thước) và triển khai giao diện OutputStream."

"Một bộ điều hợp giữa một mảng và OutputStream?"

"Đại loại thế. Đây là mã của chúng ta."

Mã số
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!");
}

"Và chúng ta sẽ làm gì với dòng này?"

"Chà, bất cứ điều gì chúng ta muốn. Ví dụ, chúng ta sẽ đảo ngược nó. Sau đó, mã sẽ như thế này:"

Mã số
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!");
}

"Thật thú vị! Bây giờ tôi bắt đầu hiểu một chút về những khả năng tuyệt vời mà các lớp học nhỏ này mang lại."
"Cảm ơn vì bài học thú vị, Bilaabo."