將輸入流InputStream轉換為String

iteye_17072發表於2011-04-15

    最近專案中用apache的httpclient中get、post、put、delete方法去請求url而這些方法請求之後響應回的資料可能很大就呼叫getResponseBodyAsString()方法,而響應後的資料要轉換成string型別,同裡也在網上看到有人需要將InputStream轉換為String物件,這裡我要跟大家說一下,這樣的InputStream需要從文字檔案(即純文字的資料檔案)中讀取內容,然後將它的內容讀出到一個String物件中。我下面直接給出程式碼,然後講解下:

package tk.hecks.blog.io;    
   
import java.io.BufferedReader;    
import java.io.IOException;    
import java.io.InputStream;    
import java.io.InputStreamReader;    
import java.util.Properties;    
   
public class StreamToString {    
   
    public static void main(String[] args) {    
         StreamToString sts = new StreamToString();    
            
        /* 
          * Get input stream of our data file. This file can be in the root of 
          * you application folder or inside a jar file if the program is packed 
          * as a jar. 
          */   
         InputStream is = sts.getClass().getResourceAsStream("/data.txt");    
   
        /* 
          * Call the method to convert the stream to string 
          */   
         System.out.println(sts.convertStreamToString(is));    
     }    
        
    public String convertStreamToString(InputStream is) {    
        /* 
          * To convert the InputStream to String we use the BufferedReader.readLine() 
          * method. We iterate until the BufferedReader return null which means 
          * there's no more data to read. Each line will appended to a StringBuilder 
          * and returned as String. 
          */   
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));    
         StringBuilder sb = new StringBuilder();    
   
         String line = null;    
        try {    
            while ((line = reader.readLine()) != null) {    
                 sb.append(line + "\n");    
             }    
         } catch (IOException e) {    
             e.printStackTrace();    
         } finally {    
            try {    
                 is.close();    
             } catch (IOException e) {    
                 e.printStackTrace();    
             }    
         }    
   
        return sb.toString();    
     }    
}   

 如果大家學習過Java IO部分的API,相信大家對上面的程式碼應該比較容易理解。我大致的講解下,主要講解convertStreamToString方法,它是主要的轉換方法。我們首先將InputStream轉換為BufferedReader物件,該物件用於讀取文字。然後我們就一行行的讀取文字資料並加入到StringBuilder中(這裡也可以用StringBuffer物件)。這裡主要主意的地方是while的結束條件是當讀取到的字串為null。然後在最後將StringBuilder物件轉換為字串返回回去。

該程式碼大家可以自己執行下試試。希望能夠幫助大家解決遇到的問題。

來源:Heck's Blog
地址:http://www.hecks.tk/httpclient-getresponsebodyasstream-stream-string/
轉載時須以連結形式註明作者和原始出處及本宣告,否則將追究法律責任,謝謝配合!

相關文章