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

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

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

相关推荐
AI+程序员在路上10 分钟前
VS Code 完全使用指南:下载、安装、核心功能与 内置AI 编程助手实战
开发语言·人工智能·windows·开源
田梓燊11 分钟前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
invicinble16 分钟前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
catchadmin25 分钟前
使用 PHP TrueAsync 改造 Laravel 协程异步化的可行路径
开发语言·php·laravel
wbs_scy31 分钟前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·开发语言
re林檎34 分钟前
算法札记——4.27
算法
ss2731 小时前
食谱推荐系统功能测试如何写?
java·数据库·spring boot·功能测试
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
数据牧羊人的成长笔记1 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
try2find1 小时前
打印ascii码报错问题
java·linux·前端