IO error while reading input message; nested exception is java.io.IOException Stream closed

I/O error while reading input message; nested exception is java.io.IOException: Stream closed

  1. I/O error while reading input message; nested exception is java.io.IOException: Stream closed
  2. com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input

今天写项目的时候偶然遇到了这个错误,导致上面两个错误的原因就是InputStream流只能读取一次

我的项目错误如下图所示,大家如果遇到了这个问题可以借鉴借鉴

image-20211122212008081

  • 获取到一个 inputStream 后,可能要多次利用它进行 read 的操作。
  • 由于流读过一次就不能再读了,而 InputStream 对象本身不能复制,而且它也没有实现Cloneable接口。

所以要想实现多次使用是实现思路如下:

  1. 先把 InputStream 转化成 ByteArrayOutputStream
  2. 后面要使用 InputStream 对象时,再从 ByteArrayOutputStream 转化回来
private String method(HttpServletRequest request) {
    ByteArrayOutputStream baos = cloneInputStream(request.getInputStream());
    // 打开两个新的输入流  
    InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());  
    InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
}
private static ByteArrayOutputStream cloneInputStream(InputStream input) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = input.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        return baos;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

但是这种适用于一些不是很大的流,因为缓存流是会消耗内存的。


**但是这种适用于一些不是很大的流,因为缓存流是会消耗内存的。**



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值