Java: PrintStream to String?
Asked Answered
C

6

131

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.

Cageling answered 19/11, 2009 at 3:18 Comment(0)
T
214

Use a ByteArrayOutputStream as a buffer:

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);
Trigg answered 19/11, 2009 at 3:21 Comment(5)
Don't forget to close the PrintStream to free all resources.Cardoon
Use new String(baos.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); available since 1.7, it doesn't throwBinkley
@Cardoon certainly a good rule of thumb, but ByteArrayOutputStream.close() "has no effect", as there are no resources to free besides the backing array which will be dealt with by the garbage collector.Historiography
ByteArrayOutputStream has toString(String charsetName), but only accept String argument. Also note that ByteArrayOutputStream is synchronized, which probably is not desirablePreter
Both the PrintStream constructor and the baos.toString method now support the Charset objects directly, so there is no more need to convert UTF_8 to UTF_8.name() first... I recommend adding import static java.nio.charset.StandardCharsets.UTF_8; so you can use UTF_8 directly as a value.Triune
P
36

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");
Prosperous answered 19/11, 2009 at 3:23 Comment(1)
Note that toString("UTF8") should be toString("UTF-8")Fustic
C
13

Why don't you use a StringWriter with a PrintWriter?

StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("Hello World!");
String output = writer.toString();
Caprine answered 21/10, 2011 at 17:31 Comment(3)
Apart from top rated answer this one doesn't bother you with charsetName.Mcilroy
This won't work. You cannot pass the PrintWriter into a function which only takes a PrintStream as argument, which was what the question was about.Tuneberg
I gave it as a suggestion on replacing the PrintStream. It's usually a good choice. If you must use a PrintStream then this i definitely not a choice. (I'm not sure why someone would vote -1 on this.. it still technically a viable option in most cases :) )Caprine
L
8

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();
Longoria answered 19/9, 2017 at 22:3 Comment(0)
V
2

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

Subclass OutputStream and wrap it in PrintStream

Venesection answered 19/11, 2009 at 3:24 Comment(0)
S
-4

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);

Sousaphone answered 2/4, 2017 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.