为 System.out 编写我们自己的包装类

"你好,阿米戈!今天,你将学习如何执行一项新任务:替换 System.out 对象。"
System.outSystem 类中名为 out 的 static 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!");
}

"太有趣了!现在,我开始对这些小型类提供的强大功能有所了解了。"

"比拉博,谢谢你给我上了有趣的一课。"

相关推荐
炸薯条!几秒前
二叉树的链式表示(2)
java·数据结构·算法
右耳朵猫AI4 分钟前
Python周刊2026W22 | Django 6.1 Alpha 1发布、Nuitka 4.1发布、PEP 831终稿、PEP 808已接受
开发语言·python·django
Tairitsu_H4 分钟前
[LC优选算法#2] 滑动窗口 | 长度最小的子数组 | 无重复字符的最长子串 | 最大连续1的个数
算法
小欣加油5 分钟前
leetcode3689最大子数组总值I
c++·算法·leetcode·职场和发展·贪心算法
半个烧饼不加肉6 分钟前
JS 底层探究-- 普通函数和构造函数
开发语言·javascript·原型模式
徐寿春12 分钟前
什么是数据倾斜
java·guava
下午写HelloWorld13 分钟前
【概念与应用】轻量级加密算法LEA、动态脱敏算法DDA、零知识证明ZKP和优化协同交互协议OCIP
算法·区块链·密码学·安全架构·零知识证明
小白不白11115 分钟前
C# WinForm 与 VP 二次开发
开发语言·c#
李白的天不白20 分钟前
一个服务器可以搭建多个网站
java·tomcat
●VON20 分钟前
AtomGit Flutter鸿蒙客户端:共享组件
java·flutter·华为·harmonyos·鸿蒙