2011-04-19 71 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)。