InputStream 转 String
发布日期:2022-02-10 11:36:52 浏览次数:29 分类:技术文章

本文共 1364 字,大约阅读时间需要 4 分钟。

  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作为中间变量而实现的

转载地址:https://blog.csdn.net/courage89/article/details/8959925 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java日期处理工具类
下一篇:java代码中读取properties文件

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2023年05月31日 13时29分41秒