记录一次流相关故障

记录一次流相关故障

1、项目中有个JSON字典文件,通过流的方式加载进来,写了个输入流转字符串的方法,idea开发环境下运行一切正常,打成jar或者war包运行时,只能加载出部分数据,一开始怀疑过运行内存分配过小、前后端数据传递时大小限制…。
通过逐步排查,找到了问题的根源,转换方法有问题。

    /**
     * 方法一(弃用)
     * 处理输入流,转成字符串
     * 这种写法有问题,is.available()不可靠,获取的文件可能被截断
     * 
     * @param is
     * @return
     */
    @Deprecated
    private static String getTextFromInputStream(InputStream is) {
        String s = "";
        try {
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            s = new String(bytes, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return s;
    }

    /**
     * 方法二
     * 处理输入流,转成字符串
     * 使用缓冲区,先写入到ByteArrayOutputStream
     *
     * @return
     */
    private static String handleStream(InputStream is) {
        String s = "";
        ByteArrayOutputStream output = null;
        try {
            output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            byte[] result = output.toByteArray();
            s = new String(result, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return s;
    }

小尾巴~~
只要有积累,就会有进步

相关推荐

  1. 记录相关故障

    2024-03-25 00:22:02       20 阅读
  2. 记录登录相关bug

    2024-03-25 00:22:02       35 阅读
  3. 记录云主机云监控客户端故障

    2024-03-25 00:22:02       11 阅读
  4. gitlab 502故障解决过程

    2024-03-25 00:22:02       20 阅读
  5. 深度学习相关记录

    2024-03-25 00:22:02       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-25 00:22:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-25 00:22:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-25 00:22:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-25 00:22:02       20 阅读

热门阅读

  1. python 画出函数图像

    2024-03-25 00:22:02       19 阅读
  2. 深度学习_相关报错解决方案

    2024-03-25 00:22:02       19 阅读
  3. a为何值是下面代码输出“成立“

    2024-03-25 00:22:02       17 阅读