记录一次流相关故障

记录一次流相关故障

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;
    }

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值