我什么时候应该使用Java的StringWriter? [英] When should I use Java's StringWriter?

查看:2670
本文介绍了我什么时候应该使用Java的StringWriter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是Java StringWriter ,我应该何时使用它?

What is a Java StringWriter, and when should I use it?

我已阅读文档和看了这里,但我不知道什么时候我应该使用它。

I have read the documentation and looked here, but I do not understand when I should use it.

推荐答案

这是一个专门的 Writer 写字符到 StringBuffer ,然后我们使用像 toString()这样的方法来获取字符串结果。

It is a specialized Writer that writes characters to a StringBuffer, and then we use method like toString() to get the string result.

当使用 StringWriter 时,您要写入字符串,但API期望 Writer Stream 。这是一个妥协,只有当你需要时才使用 StringWriter ,因为 StringBuffer / StringBuilder 写字符更自然,更容易,这应该是你的首选。

When StringWriter is used is that you want to write to a string, but the API is expecting a Writer or a Stream. It is a compromised, you use StringWriter only when you have to, since StringBuffer/StringBuilder to write characters is much more natural and easier,which should be your first choice.

这是两个典型的好用例 StringWriter

Here is two of a typical good case to use StringWriter

1.将堆栈跟踪转换为 String ,因此我们可以轻松地记录它。

1.Converts the stack trace into String, so that we can log it easily.

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 上的字符,以便我们可以获得 String 稍后,使用 Apache commons IOUtils #copy

2.Another case will be when we need to copy from an InputStream to chars on a Writer so that we can get String later, using Apache commons IOUtils#copy :

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);//copy the stream into the StringWriter
String result = writer.toString();

这篇关于我什么时候应该使用Java的StringWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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