将输入流InputStream转换为String

本文介绍了一种将InputStream转换为String的方法,通过使用BufferedReader逐行读取数据,并将其追加到StringBuilder中,最终返回字符串形式的数据。适用于处理HTTP响应等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    最近项目中用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/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值