将输入流InputStream转换为String

来源:互联网 发布:网络编程语言 编辑:程序博客网 时间:2024/05/24 06:27
最近项目中用apache的httpclient中get、post、put、delete方法去请求url而这些方法请求之后响应回的数据可能很大就调用getResponseBodyAsString()方法,而响应后的数据要转换成string类型,同里也在网上看到有人需要将InputStream转换为String对象,这里我要跟大家说一下,这样的InputStream需要从文本文件(即纯文本的数据文件)中读取内容,然后将它的内容读出到一个String对象中。我下面直接给出代码,然后讲解下。
view plainprint?
  1. package tk.hecks.blog.io;      
  2.      
  3. import java.io.BufferedReader;      
  4. import java.io.IOException;      
  5. import java.io.InputStream;      
  6. import java.io.InputStreamReader;      
  7. import java.util.Properties;      
  8.      
  9. public class StreamToString {      
  10.      
  11.     public static void main(String[] args) {      
  12.          StreamToString sts = new StreamToString();      
  13.               
  14.         /*  
  15.           * Get input stream of our data file. This file can be in the root of  
  16.           * you application folder or inside a jar file if the program is packed  
  17.           * as a jar.  
  18.           */     
  19.          InputStream is = sts.getClass().getResourceAsStream("/data.txt");      
  20.      
  21.         /*  
  22.           * Call the method to convert the stream to string  
  23.           */     
  24.          System.out.println(sts.convertStreamToString(is));      
  25.      }      
  26.           
  27.     public String convertStreamToString(InputStream is) {      
  28.         /*  
  29.           * To convert the InputStream to String we use the BufferedReader.readLine()  
  30.           * method. We iterate until the BufferedReader return null which means  
  31.           * there's no more data to read. Each line will appended to a StringBuilder  
  32.           * and returned as String.  
  33.           */     
  34.          BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
  35.          StringBuilder sb = new StringBuilder();      
  36.      
  37.          String line = null;      
  38.         try {      
  39.             while ((line = reader.readLine()) != null) {      
  40.                  sb.append(line + "\n");      
  41.              }      
  42.          } catch (IOException e) {      
  43.              e.printStackTrace();      
  44.          } finally {      
  45.             try {      
  46.                  is.close();      
  47.              } catch (IOException e) {      
  48.                  e.printStackTrace();      
  49.              }      
  50.          }      
  51.      
  52.         return sb.toString();      
  53.      }      
  54. }     

如果大家学习过Java IO部分的API,相信大家对上面的代码应该比较容易理解。我大致的讲解下,主要讲解convertStreamToString方法,它是主要的转换方法。我们首先将InputStream转换为BufferedReader对象,该对象用于读取文本。然后我们就一行行的读取文本数据并加入到StringBuilder中(这里也可以用StringBuffer对象)。这里主要主意的地方是while的结束条件是当读取到的字符串为null。然后在最后将StringBuilder对象转换为字符串返回回去。

该代码大家可以自己运行下试试。希望能够帮助大家解决遇到的问题。whiteeye


来源:Heck's Blog
地址:http://www.hecks.tk/httpclient-getresponsebodyasstream-stream-string/
0 0