How to convert stream results to string

Deadly 提交于 2019-11-27 01:49:38

问题


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


回答1:


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



回答2:


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



回答3:


You can use a StringWriter in this way :

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


来源:https://stackoverflow.com/questions/13217657/how-to-convert-stream-results-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!