Android中InputStream与String,Byte之间互转

在Android开发中,通常使用HttpsURLConnection获取InputStream。本文介绍如何将InputStream转换为String和Byte,涉及ByteArrayOutputStream及缓冲区的使用。

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

我们大家在学习Android的时候,客户端进行Http请求的时候一般通过HttpsURLConnection.getInputStream()来获得一个Inputstream,

一般我们需要将这个流转换的成String,查了API后发现Inputstream没有转换成String的方法,一次我们需要自己写方法来转换。

本文通过代码的方式来写出InputStream与String,Byte之间互转。

1、Inputstream转换成String,这里需要借助一个ByteArrayOutputStream对象,一个byte[  ] 作为缓冲区,方法如下:

<span style="font-size:18px;">public static String InputStreamTOString(InputStream in) throws Exception{  
          
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];  
        int count = -1;  
        while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return new String(outStream.toByteArray(),"ISO-8859-1");  
    }  </span>
2、将InputStream转换成某种字符编码的String ,代码如下

 public static String InputStreamTOString(InputStream in,String encoding) throws Exception{  
          
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];  
        int count = -1;  
        while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return new String(outStream.toByteArray(),"ISO-8859-1");  
    }  
3、将String转换成InputStream
public static InputStream StringTOInputStream(String in) throws Exception{  
          
        ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1"));  
        return is;  
    }  
4、将InputStream转换成byte数组 

 public static byte[] InputStreamTOByte(InputStream in) throws IOException{  
          
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];  
        int count = -1;  
        while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return outStream.toByteArray();  
    }  

5、将byte数组转换成InputStream 

public static InputStream byteTOInputStream(byte[] in) throws Exception{  
          
        ByteArrayInputStream is = new ByteArrayInputStream(in);  
        return is;  
    }  
6、将byte数组转换成String  

<span style="font-size:18px;"> public static String byteTOString(byte[] in) throws Exception{  
          
        InputStream is = byteTOInputStream(in);  
        return InputStreamTOString(is);  
    }  </span>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值