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

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

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

相关推荐
Godspeed Zhao4 分钟前
从零开始学AI16——SVM
算法·机器学习·支持向量机
yaoxin5211238 分钟前
406. Java 文件操作基础 - 字符与二进制流
java·开发语言·python
江屿风14 分钟前
C++OJ题经验总结(竞赛)1
开发语言·c++·笔记·算法
happymaker062615 分钟前
SpringBoot学习日记——DAY02(SpringBoot整合Swagger3)
java·spring boot·学习
nebula-AI16 分钟前
人工智能导论:模型与算法(核心技术)
人工智能·深度学习·神经网络·算法·机器学习·集成学习·sklearn
阿坤带你走近大数据27 分钟前
Java中的JVM、类加载记住、多线程、性能优化的概念
java·jvm·性能优化
运筹vivo@34 分钟前
LeetCode 2405. 子字符串的最优划分
c++·算法·leetcode·职场和发展·哈希表
数智工坊35 分钟前
视觉-语言-动作模型解剖学:从模块、里程碑到核心挑战
论文阅读·人工智能·深度学习·算法·transformer
鱼鳞_38 分钟前
苍穹外卖-Day04
java