70

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

嗨,我想将此 BufferedInputStream 转换为我的字符串。我怎样才能做到这一点?

BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream() );
String a= in.read();
4

5 回答 5

51
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);
于 2011-04-19T09:00:27.990 回答
34

番石榴

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

使用Commons / IO

IOUtils.toString(inputStream, "UTF-8")
于 2011-04-19T09:03:27.647 回答
19

我建议你使用 apache commons IOUtils

String text = IOUtils.toString(sktClient.getInputStream());
于 2011-04-19T09:04:48.140 回答
11

请按照代码

让我知道结果

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

于 2011-04-19T08:59:09.527 回答
5

如果你不想自己写所有的东西(你不应该真的) - 使用一个为你做这件事的库。

Apache commons-io就是这样做的。

如果您想要更好的控制,请使用 IOUtils.toString(InputStream) 或 IOUtils.readLines(InputStream)。

于 2011-04-19T09:05:09.023 回答