如何将InputStream转换为String

 

如何将InputStream转换为String

2009-02-05 作者:
zhangtaolv

在网上看到有人需要将InputStream转换为String对象,这里我要跟大家说一下,这样的InputStream需要从文本文件(即纯文本的数据文件)中读取内容,然后将它的内容读出到一个String对象中。我下面直接给出代码,然后讲解下:

Java代码
  1. package  cn.jcourse.example.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对象转换为字符串返回回去。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值