如果我从java.io.InputStream开始,那么将整个流读出为字符串的最简单方法是什么(假设utf-8)?
这应该很容易,但我主要是一个C#用户,谷歌在这方面让我失望了。谢谢。
发布于 2009-12-12 08:01:30
根据您喜欢的许可证,它是一个带有雅加达-Commons IO库的one liner。
发布于 2009-12-12 07:51:40
在Java中,从流中读取/写入是非常痛苦的。
public static String getStreamContents(InputStream stream) throws IOException {
StringBuilder content = new StringBuilder()
Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"))
String lineSeparator = System.getProperty("line.separator");
try {
String line
while ((line = reader.readLine()) != null) {
content.append(line + lineSeparator)
}
return content.toString()
} finally {
reader.close()
}
}
发布于 2009-12-13 02:09:40
使用Commons-IO可能是最好的选择。出于您的兴趣,另一种方法是复制所有字节,然后将其转换为字符串。
public static String readText(InputStream is, String charset) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
for(int len;(len = is.read(bytes))>0;)
baos.write(bytes, 0, len);
return new String(baos.toByteArray(), charset);
}
https://stackoverflow.com/questions/1891606
复制相似问题