我有一个函数,它接受某种类型的对象和要打印到的PrintStream
,并输出该对象的表示。如何在字符串中捕获此函数的输出?具体地说,我想像在toString
方法中一样使用它。
发布于 2009-11-19 11:22:00
使用ByteArrayOutputStream
作为缓冲区:
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);
发布于 2009-11-19 11:23:05
您可以使用传入构造函数的ByteArrayOutputStream来构造PrintStream,稍后可以使用该构造函数获取写入PrintStream的文本。
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
...
String output = os.toString("UTF8");
发布于 2011-10-22 01:31:09
为什么不把StringWriter和PrintWriter一起使用呢?
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("Hello World!");
String output = writer.toString();
https://stackoverflow.com/questions/1760654
复制相似问题