
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 closedI/O error while reading input message; nested exception is java.io.IOException: Stream closedcom.fasterxml.
·
I/O 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
- com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
今天写项目的时候偶然遇到了这个错误,导致上面两个错误的原因就是InputStream流只能读取一次
我的项目错误如下图所示,大家如果遇到了这个问题可以借鉴借鉴
- 获取到一个
inputStream
后,可能要多次利用它进行 read 的操作。 - 由于流读过一次就不能再读了,而
InputStream
对象本身不能复制,而且它也没有实现Cloneable
接口。
所以要想实现多次使用是实现思路如下:
- 先把
InputStream
转化成ByteArrayOutputStream
- 后面要使用
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;
}
}
但是这种适用于一些不是很大的流,因为缓存流是会消耗内存的。
**但是这种适用于一些不是很大的流,因为缓存流是会消耗内存的。**
更多推荐
所有评论(0)