zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    django-02框架-配置、静态文件和路由
    django-01框架-工程搭建
    python虚拟环境安装
    linux推送文件到另一台主机
    python2问题收集
    python diff json方法
    Linux expect详解
    python scp到远端机器
    shell远程执行命令(命令行与脚本)
    git操作
  • 原文地址:https://www.cnblogs.com/-lpf/p/4236440.html
Copyright © 2011-2022 走看看