不重复造轮子。
最可靠的方法,或者使用Apache
commons IOUtils
这样简单几行代码就搞定了
StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, encoding); String theString = writer.toString();
或者
String theString = IOUtils.toString(inputStream, encoding)//这种方法事实上封装了上面的方法,降低了一个參数
假设不想引入Apache库。也能够这样做
static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A"); return s.hasNext() ? s.next() : "";}
stackoverflow讨论地址
http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
专栏介绍:
很喜欢stackoverflow,总能在上面找到疑难杂症的解决的方法。
偶然发现该站点有一个热度榜单。于是精选了热度较高的一些问题。阅读每一个问题的答案,然后依照自己的理解梳理出来。
因此,这些文章不是真正的翻译,而是依照自己的理解做了一些增删和个人风格的润色,希望能把上面的讨论。更精简有效地分享给大家。
如需转载,请注明原文地址