InputStream 转 String

  1. /**  将String转换成InputStream      */  
  2.     public static InputStream StringTOInputStream(String in) throws Exception{  
  3.           
  4.         ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1"));  
  5.         return is;  
  6.     }  
  7.       
  8.     /**   将InputStream转换成byte数组       */  
  9.     public static byte[] InputStreamTOByte(InputStream in) throws IOException{  
  10.           
  11.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  12.         byte[] data = new byte[BUFFER_SIZE];  
  13.         int count = -1;  
  14.         while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
  15.             outStream.write(data, 0, count);  
  16.           
  17.         data = null;  
  18.         return outStream.toByteArray();  
  19.     }  
  20.       
  21.     /**  将byte数组转换成InputStream      */  
  22.     public static InputStream byteTOInputStream(byte[] in) throws Exception{  
  23.           
  24.         ByteArrayInputStream is = new ByteArrayInputStream(in);  
  25.         return is;  
  26.     }  
  27.       
  28.     /**  
  29.      * 将byte数组转换成String  
  30.      * @param in  
  31.      * @return  
  32.      * @throws Exception  
  33.      */  
  34.     public static String byteTOString(byte[] in) throws Exception{  
  35.           
  36.         InputStream is = byteTOInputStream(in);  
  37.         return InputStreamTOString(is);  
  38.     } 

       /*将InputStream转成指定编码过的String/   

  1.    public static String InputStreamTOString(InputStream in) throws Exception{  
  2.           
  3.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  4.         byte[] data = new byte[BUFFER_SIZE];  
  5.         int count = -1;  
  6.         while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
  7.             outStream.write(data, 0, count);  
  8.           
  9.         data = null;  
  10.         return new String(outStream.toByteArray(),"ISO-8859-1");  
  11.     }
如上InputStream转byte[]或者是String,都是借助了byte[]和OutPutStream作为中间变量而实现的




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值