2011-04-19 38 views

回答

32
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); 
+4

一个小错误。在while循环中,每次迭代都应该附加一个循环。它应该是+ =而不是=。即:strFileContents + =新字符串(内容,0,bytesRead); – 2014-06-26 20:54:46

+3

@ JJ_Coder4Hire这不是唯一的错误,这段代码依赖于字符串编码在bytesRead标记处有一个边界的机会(对于ASCII,这是一个好的假设** ONLY **)。 – chacham15 2014-07-15 07:56:09

+0

我不得不把'System.out.print(strFileContents);'内部循环,否则只显示我的html响应的最后一部分。 btw谢谢 – SaganTheBest 2015-01-14 14:54:44

1

快速的谷歌搜索“java bufferedinputstream string”引发了大量的例子。 This人应该做的伎俩。

7

请下面的代码

让我知道结果

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

+0

不需要铸造。 BufferedInputStream是一个InputStream – 2011-04-19 09:06:00

+0

谢谢。更新 – DroidBot 2011-04-19 09:27:12

+1

“谢谢,Kariyachan”我记得那个猫来自“来自U.N.C.L.E.的人” - 他现在是程序员? – 2014-04-02 17:42:10

24

随着Guava

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

随着Commons/IO

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

我建议你使用Apache的百科全书IOUtils

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

如果你不想自己写的这一切(你应该不是真的) - 使用库为你做到这一点。

Apache commons-io就是这样做的。

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