Java: PrintStream to String?

三世轮回 提交于 2019-12-02 15:41:08
ChssPly76

Use a ByteArrayOutputStream as a buffer:

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

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (PrintStream ps = new PrintStream(baos, true, "UTF-8")) {
        yourFunction(object, ps);
    }
    String data = new String(baos.toByteArray(), StandardCharsets.UTF_8);

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 os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
...
String output = os.toString("UTF8");

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

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();
Kamil Szot

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

Subclass OutputStream and wrap it in PrintStream

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

Ans: Scanner inSS = new Scanner(myStrLine);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!