java.lang.IllegalStateException: getOutputStream() has already been called for this response

在实现下载功能的时候,如果碰到这个异常:java.lang.IllegalStateException: getOutputStream() has already been called for this response

servlet/action中:

 1 // 读取文件

 2         InputStream in = new FileInputStream(fullFileName);

 3         OutputStream ou = response.getOutputStream();

 4 

 5         // 写文件

 6         int b;

 7         while ((b = in.read()) != -1) {

 8             ou.write(b);

 9         }

10         in.close();

11 ou.flush();
12         ou.close();
 
  

在ou.flush()被注释掉的情况下就会出现在异常;

flush() 是把缓冲区的数据强行输出, 主要用在IO中,即清空缓冲区数据,一般在读写流(stream)的时候,数据是先被读到了内存中,再把数据写到文件中,当你数据读完的时候不代表你的数据已经写完了,因为还有一部分有可能会留在内存这个缓冲区中。这时候如果你调用了close()方法关闭了读写流,那么这部分数据就会丢失,所以应该在关闭读写流之前先flush()。

jsp中出现该异常的解决方法:

在类似上面代码的位置加入

out.clear();
out = pageContext.pushBody();

 

你可能感兴趣的:(java.lang.IllegalStateException: getOutputStream() has already been called for this response)