BufferedInputStream到字符串转换?

Har*_*der 54 java

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

嗨,我想把这个BufferedInputStream放到我的字符串中,我该怎么做?

BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream() );
String a= in.read();
Run Code Online (Sandbox Code Playgroud)

Nir*_*ond 47

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);
Run Code Online (Sandbox Code Playgroud)

  • 一个小虫子.在while循环中,您应该在每次迭代时附加.它应该是+ =而不是=.ie:strFileContents + = new String(contents,0,bytesRead); (5认同)
  • @JJ_Coder4Hire不是唯一的错误,这段代码依赖于字符串编码在bytesRead标记处有边界的机会(这是一个好的假设**仅适用于ASCII). (3认同)

Sea*_*oyd 30

番石榴:

new String(ByteStreams.toByteArray(inputStream),Charsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)

使用Commons/IO:

IOUtils.toString(inputStream, "UTF-8")
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 17

我建议你使用apache commons IOUtils

String text = IOUtils.toString(sktClient.getInputStream());
Run Code Online (Sandbox Code Playgroud)


Dro*_*Bot 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 "";
            }
        }
Run Code Online (Sandbox Code Playgroud)

谢谢,Kariyachan

  • "谢谢,Kariyachan"我记得那只来自"UNCLE的男人"的猫 - 他现在是程序员吗? (2认同)

Era*_*rel 5

如果您不想自己编写(并且您不应该这样做) - 请使用为您执行此操作的库.

Apache commons-io就是这么做的.

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