解决方法
它是一个专门的Writer,它将字符写入StringBuffer,然后我们使用类似toString()的方法来获取字符串结果.
当使用StringWriter时,您希望写入字符串,但API需要Writer或Stream.它是一个妥协的,你只有在必须时才使用StringWriter,因为StringBuffer / StringBuilder写字符更加自然和容易,这应该是你的首选.
以下是使用StringWriter的两个典型案例
1.将堆栈跟踪转换为String,以便我们可以轻松记录.
StringWriter sw = new StringWriter();//create a StringWriter PrintWriter pw = new PrintWriter(sw);//create a PrintWriter using this string writer instance t.printStackTrace(pw);//print the stack trace to the print writer(it wraps the string writer sw) String s=sw.toString(); // we can now have the stack trace as a string
2.另一种情况是当我们需要从InputStream复制到Writer上的字符时,以便我们以后可以使用Apache commons IOUtils#copy获取String:
StringWriter writer = new StringWriter(); IoUtils.copy(inputStream,writer,encoding);//copy the stream into the StringWriter String result = writer.toString();