如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
当前回答
注意:这可能不是个好主意。此方法使用递归,因此将非常快地命中StackOverflowError:
public String read (InputStream is) {
byte next = is.read();
return next == -1 ? "" : next + read(is); // Recursive part: reads next byte recursively
}
其他回答
这是一个改编自org.apache.commons.io.IOUtils源代码的答案,适用于那些想要apache实现但不想要整个库的人。
private static final int BUFFER_SIZE = 4 * 1024;
public static String inputStreamToString(InputStream inputStream, String charsetName)
throws IOException {
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
char[] buffer = new char[BUFFER_SIZE];
int length;
while ((length = reader.read(buffer)) != -1) {
builder.append(buffer, 0, length);
}
return builder.toString();
}
此代码段位于\sdk\samples\android-19\connection\NetworkConnect\NetworkConnectSample\src\main\java.com\example\android\NetworkConnect\MainActivity.java中,该代码段根据Apache许可证2.0版授权,由Google编写。
/** Reads an InputStream and converts it to a String.
* @param stream InputStream containing HTML from targeted site.
* @param len Length of string that this method returns.
* @return String concatenated according to len parameter.
* @throws java.io.IOException
* @throws java.io.UnsupportedEncodingException
*/
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
与Okio一起:
String result = Okio.buffer(Okio.source(inputStream)).readUtf8();
InputStream is = Context.openFileInput(someFileName); // whatever format you have
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[8192];
for (int bytesRead; (bytesRead = is.read(b)) != -1;) {
bos.write(b, 0, bytesRead);
}
String output = bos.toString(someEncoding);
最简单的方法,一行:
public static void main(String... args) throws IOException {
System.out.println(new String(Files.readAllBytes(Paths.get("csv.txt"))));
}