将控制台输出重定向到 Java 中的字符串 [英] Redirect console output to string in Java

查看:41
本文介绍了将控制台输出重定向到 Java 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它的返回类型是void,它直接在控制台上打印.

I have one method whose return type is void and it prints directly on console.

但是我需要一个字符串中的输出,以便我可以处理它.

However I need that output in a String so that I can work on it.

由于我无法对返回类型为 void 的方法进行任何更改,因此我必须将该输出重定向到字符串.

As I can't make any changes to the method with return type void I have to redirect that output to a String.

如何在 Java 中重定向它?

How can I redirect it in Java?

推荐答案

如果函数正在打印到 System.out,您可以使用 System.setOut 捕获该输出code> 方法将 System.out 更改为您提供的 PrintStream.如果您创建一个连接到 ByteArrayOutputStreamPrintStream,那么您可以将输出捕获为 String.

If the function is printing to System.out, you can capture that output by using the System.setOut method to change System.out to go to a PrintStream provided by you. If you create a PrintStream connected to a ByteArrayOutputStream, then you can capture the output as a String.

示例:

// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());

这个程序只打印一行:

Here: Foofoofoo!

这篇关于将控制台输出重定向到 Java 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆