InputStream转为String的两种方式 |
您所在的位置:网站首页 › 将csdn文章内容转成pdf文件使用教程视频 › InputStream转为String的两种方式 |
一. 背景 在项目开发过程中,经常会从某种存储介质中读取到InputStream流中,之后我们需要将InputStream流转换为String字符串的形式,然后使用这个String串进行后面的操作。经过查询,整理了如下两种方式。 二. InputStream转为String的方式 1. 使用 inputStream.read 和 ByteArrayOutputStream 优点:速度快 public static String getStringByInputStream_1(InputStream inputStream){ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { byte[] b = new byte[10240]; int n; while ((n = inputStream.read(b)) != -1) { outputStream.write(b, 0, n); } } catch (Exception e) { try { inputStream.close(); outputStream.close(); } catch (Exception e1) { } } return outputStream.toString(); }2. 使用 InputStreamReader 和 BufferedReader public static String getStringByInputStream_2(InputStream inputStream){ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); try { StringBuilder result = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line); } return result.toString(); } catch (Exception e) { try { inputStream.close(); bufferedReader.close(); } catch (Exception e1) { } } return null; } 三. 参考文献11种将InputStream转换成String的方法以及性能分析 ———————————————— 版权声明:本文为CSDN博主「zijikanwa」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/zijikanwa/article/details/108850332 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |