Android中InputStream与String,Byte之间互转

来源:互联网 发布:完美网络刷销量 编辑:程序博客网 时间:2024/06/05 06:23

我们大家在学习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>





0 0