InputStream转为String的两种方式

时间:2025-03-11 16:18:21

一. 背景
在项目开发过程中,经常会从某种存储介质中读取到InputStream流中,之后我们需要将InputStream流转换为String字符串的形式,然后使用这个String串进行后面的操作。经过查询,整理了如下两种方式。
二. InputStream转为String的方式
1. 使用 和 ByteArrayOutputStream
优点:速度快

public static String getStringByInputStream_1(InputStream inputStream){
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
         byte[] b = new byte[10240];
         int n;
         while ((n = (b)) != -1) {
             (b, 0, n);
         }
     } catch (Exception e) {
         try {
             ();
             ();
         } catch (Exception e1) {
         }
     }
     return ();
}

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 = ()) != null) {
            (line);
        }
        return ();
    } catch (Exception e) {
        try {
            ();
            ();
        } catch (Exception e1) {
        }
    }
    return null;
}

三. 参考文献

11种将InputStream转换成String的方法以及性能分析


————————————————
版权声明:本文为****博主「zijikanwa」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:/zijikanwa/article/details/108850332

相关文章