如何将流结果转换为字符串

时间:2012-11-04 10:12:22

标签: java dom filestream

我想将流结果输出转换为字符串,因为我想要 在Junit中使用它我认为我需要使用字符串编写器但是 我不确定如何使用它。

StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);

由于 费多尔

3 个答案:

答案 0 :(得分:32)

查看并学习使用StreamResult类(http://java.sun.com/javase/6/docs/api/)的javadoc。 StreamResult的一个构造函数将Writer对象作为参数。您将看到Writer的一个子类是StringWriter。因此,要从写入StreamResult的内容中获取字符串,您可以构造StringWriter,将其放入StreamResult,将Source()转换为StreamResult并从StringWriter获取字符串。

//create a StringWriter for the output
StringWriter outWriter = new StringWriter();
StreamResult result = new StreamResult( outWriter );
...
transformer.transform( source, result );  
StringBuffer sb = outWriter.getBuffer(); 
String finalstring = sb.toString();

答案 1 :(得分:31)

StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String output = writer.toString();

答案 2 :(得分:3)

您可以这样使用StringWriter

StringWriter sw = (StringWriter) result.getWriter(); 
StringBuffer sb = sw.getBuffer(); 
String finalstring = sb.toString();