这是我在刷新ServletOutputStream
时遇到的异常。它不会在每个请求中发生,因此我无法重现它。
java.lang.NullPointerException
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:215)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:480)
at org.apache.coyote.http11.InternalOutputBuffer.flush(InternalOutputBuffer.java:119)
at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:805)
at org.apache.coyote.Response.action(Response.java:174)
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:366)
at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:333)
at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:101)
at darshan.HttpRequestHandler.returnResponse(HttpRequester.java:117)
HttpRequester.java:
private void returnResponse(HttpServletResponse response , String responseStr)
{
InputStream in = null;
ServletOutputStream out = null;
try
{
in = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
response.setContentLength(responseStr.length());
out = response.getOutputStream();
byte[] outputByte = new byte[4096];
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
out.flush(); //<-- Exception at this line
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
此错误的任何解决方案???
答案 0 :(得分:4)
您的代码不需要在输入或输出流上调用flush
或close
。 servlet容器将为您进行冲洗和关闭。
有时需要进行手动冲洗呼叫的角落情况,但这不是其中之一。但是,在其中任何一个上调用close
都不是一个好主意,并且可能会在tomcat中触发导致异常的错误状态。
请参阅Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?
答案 1 :(得分:0)
这里你可能在最后一个块中写入内容长度,因为它可能读取少于4096bytes
byte[] outputByte = new byte[4096];
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}