BufferedInputStream 到 String 转换 BufferedInputStream? ?

可能的复制品:
在 Java 中,如何读取/转换 InputStream 为字符串?

嗨,我想把这个 BufferedInputStream 转换成我的字符串。我该怎么做呢?

BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream() );
String a= in.read();
75475 次浏览

请遵循代码

告诉我结果

public String convertStreamToString(InputStream is)
throws IOException {
/*
* To convert the InputStream to String we use the
* Reader.read(char[] buffer) method. We iterate until the
35.         * Reader return -1 which means there's no more data to
36.         * read. We use the StringWriter class to produce the string.
37.         */
if (is != null) {
Writer writer = new StringWriter();


char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
return writer.toString();
} else {
return "";
}
}

谢谢, Kariyachan

BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream());
byte[] contents = new byte[1024];


int bytesRead = 0;
String strFileContents;
while((bytesRead = in.read(contents)) != -1) {
strFileContents += new String(contents, 0, bytesRead);
}


System.out.print(strFileContents);

番石榴:

new String(ByteStreams.toByteArray(inputStream),Charsets.UTF_8);

公共资源/业主立案法团:

IOUtils.toString(inputStream, "UTF-8")

我建议你使用 apache commons IOUtils

String text = IOUtils.toString(sktClient.getInputStream());

如果你不想自己一个人完成(实际上也不应该) ,那就使用一个可以帮你完成的库。

Apache commons-io 就是这样做的。

如果希望获得更好的控制,可以使用 IOUtils.toString (InputStream)或 IOUtils.readLines (InputStream)。