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

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

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

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

相关推荐
mlidongfeng8 分钟前
【学习笔记】【NV】GIN
开发语言·php
Ivanqhz10 分钟前
KV Cache
服务器·数据库·人工智能·深度学习·算法
H.莓飛12 分钟前
【数据结构】二叉树
linux·数据结构·算法
大圣编蚕16 分钟前
Spring AOP 失效排查:从原理到实战的完整指南
java·后端·spring
Omics Pro19 分钟前
~30,000+引用!理论2005,R包2008,多组学集成AI增强
开发语言·数据库·人工智能·算法·机器学习·自然语言处理·r语言
EatFan24 分钟前
MCP 从概念到落地:Java(Spring AI Alibaba)与 .NET 双栈接入实操对比
java·人工智能·后端·spring·.net·java后端·mcp
专业程序开发源25 分钟前
springboot全民健身和饮食健康管理系统29158-计算机课程设计、毕业设计
java·spring boot·后端·python·django·php·课程设计
ym hyd 11127 分钟前
汽车零部件缺陷管理系统源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·汽车·毕设
小道士写程序28 分钟前
Windows Rust 环境安装指导
开发语言·windows·rust
xh didida29 分钟前
Linux -- 进程概念
linux·服务器·开发语言·c++