I have a function that takes an object of a certain type, and a PrintStream
to 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 toString
method.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
回答2:
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");
回答3:
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();
回答4:
Maybe this question might help you: Get an OutputStream into a String
Subclass OutputStream and wrap it in PrintStream
回答5:
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);