How do I convert an InputStream to a String in Java?
Suppose I have an InputStream
that contains text data, and I want to convert this to a String
(for example, so I can write the contents of the stream to a log file).
What is the easiest way to take the InputStream
and convert it to a String
?
public String convertStreamToString(InputStream is) {
// ???
}
这是我的版本,
public static String readString(InputStream inputStream) throws IOException {
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}
如果你想简单而可靠地做到这一点,我建议使用Apache Jakarta Commons IO库IOUtils.toString(java.io.InputStream, java.lang.String)
方法。
String text = new Scanner( inputStream).useDelimiter("A").next();
这里更多
链接地址: http://www.djcxy.com/p/78368.html