JavaIO操作-将InputStream转换为String

阿超 发表于 2009-08-22 23:52 | 来源: | 阅读 587 次

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

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

该代码大家可以自己运行下试试。希望能够帮助大家解决遇到的问题,大家可以在Java豆上面给我留言!

关键字:
喜欢Java豆技术站点的文章,那就通过 RSS Feed 功能订阅阅读吧!

我要评论

*

* 绝不会泄露



返回首页 | 关于我们 | 联系我们 | 广告合作 | 网站地图 | 友情链接 | 版权声明 | 模板设计