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

24
我想把流结果输出转换成字符串,因为我想在Junit中使用它。我认为我需要使用字符串写入器,但是我不确定该如何使用它。
StreamResult result = new StreamResult(new File("C:\\file.xml"));
transformer.transform(source, result);

谢谢Fedor

3个回答

41

请查看并学习StreamResult类的javadocs (http://java.sun.com/javase/6/docs/api/)。 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();

你好Timo,谢谢。但是我应该把转换器放在哪里呢?StreamResult result = new StreamResult(new File("C:\file.xml")); - user1578363
你可以使用StreamResult result = new StreamResult(new File("C:\file.xml"));将结果写入文件,也可以使用StreamResult result = new StreamResult( outWriter );将结果写入StringWriter。如果你只想要字符串,为什么还要使用文件呢? - Timo Hahn
“source” 代表什么? - Patrick W. McMahon
我猜测 source 是正在进行转换的 XML。 - james.garriss

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

3
您可以这样使用StringWriter

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

这就是我在寻找的。 - divine
使用缓冲区和不使用缓冲区有什么区别,例如@nosid的回答中提到的? - Charles Follet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接