Java:PrintStream 到字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1760654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:23:35  来源:igfitidea点击:

Java: PrintStream to String?

javastringprintstream

提问by Nick Heiner

I have a function that takes an object of a certain type, and a PrintStreamto which to print, and outputs a representation of that object. How can I capture this function's output in a String? Specifically, I want to use it as in a toStringmethod.

我有一个函数,它接受某种类型的对象和一个PrintStream要打印的对象,并输出该对象的表示。如何在字符串中捕获此函数的输出?具体来说,我想在toString方法中使用它。

采纳答案by ChssPly76

Use a ByteArrayOutputStreamas a buffer:

使用 aByteArrayOutputStream作为缓冲区:

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final String utf8 = StandardCharsets.UTF_8.name();
    try (PrintStream ps = new PrintStream(baos, true, utf8)) {
        yourFunction(object, ps);
    }
    String data = baos.toString(utf8);

回答by Asaph

You can construct a PrintStream with a ByteArrayOutputStream passed into the constructor which you can later use to grab the text written to the PrintStream.

您可以使用传递给构造函数的 ByteArrayOutputStream 构造 PrintStream,稍后您可以使用它来获取写入 PrintStream 的文本。

ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
...
String output = os.toString("UTF8");

回答by Kamil Szot

Maybe this question might help you: Get an OutputStream into a String

也许这个问题可能对你有帮助: Get an OutputStream into a String

Subclass OutputStream and wrap it in PrintStream

子类 OutputStream 并将其包装在 PrintStream 中

回答by user7805633

Define and initialize a Scanner variable named inSS that creates an input string stream using the String variable myStrLine.

定义并初始化名为 inSS 的 Scanner 变量,该变量使用 String 变量 myStrLine 创建输入字符串流。

Ans: Scanner inSS = new Scanner(myStrLine);

Ans: Scanner inSS = new Scanner(myStrLine);

回答by Kaelan Dawnstar

A unification of previous answers, this answer works with Java 1.7 and after. Also, I added code to close the Streams.

先前答案的统一,此答案适用于 Java 1.7 及更高版本。此外,我添加了代码来关闭流。

final Charset charset = StandardCharsets.UTF_8;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, charset.name());
yourFunction(object, ps);
String content = new String(baos.toByteArray(), charset);
ps.close();
baos.close();