如何将流结果转换为字符串 [英] How to convert stream results to string

查看:110
本文介绍了如何将流结果转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将流结果输出转换为字符串,因为我想要
在Junit中使用它我认为我需要使用字符串作者,但
我不知道如何使用它。 / p>

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

感谢
Fedor

解决方案

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

  //为输出创建一个StringWriter 
StringWriter outWriter = new StringWriter();
StreamResult result = new StreamResult(outWriter);
...
transformer.transform(source,result);
StringBuffer sb = outWriter.getBuffer();
String finalstring = sb.toString();


I want to convert the stream result output to string since I want to use it in Junit I think that I need to use the string writer but Im not sure how exactly to use it.

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

Thanks Fedor

解决方案

Have a look at and learn to use the javadocs of the StreamResult class (http://java.sun.com/javase/6/docs/api/). One of the constructors of StreamResult takes a Writer object as a parameter. You will see that one of the sub-classes of Writer is StringWriter. So to obtain a string from what is written to the StreamResult, you can construct a StringWriter, put it into the StreamResult, transform() the Source to the StreamResult and get the string from the 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();

这篇关于如何将流结果转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆