nixon1333
nixon1333

Reputation: 531

OutputStreamWriter java can't store into string

transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));

I'm using this to generate the output to console. I want to store the output to a sting. I don't know how to do. Can any one help me? :(

Thanks in advance

Upvotes: 3

Views: 8085

Answers (3)

clearwater
clearwater

Reputation: 514

For example use this (it avoids encoding the string):

StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String str = writer.getBuffer().toString();

Upvotes: 7

Hakan Serce
Hakan Serce

Reputation: 11266

Use StringWriter class instead of OutputStreamWriter.

Upvotes: 2

Tom
Tom

Reputation: 4093

One solution could look like this:

ByteArrayOutputStream out = new ByteArrayOutputStream();
transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(out, "UTF-8")));
String string = new String(out.toByteArray(), "UTF-8");

Upvotes: 0

Related Questions