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

在执行下述代码时报错,

OutputStream out = getResponse().getOutputStream();

原因为代码中有打开的Response.getWriter(),未关闭,因调用点较多,不好一一排查。

通过查看代码,看到response中的usingWriter=true,随即想办法将该标志位设置为false。

response.reset(); 即可,注意reset后缓存消失,设置消失。

OutputStream和Writer在一个response中不能同时获得。

具体内容见:

public static void filedownShowEX(String fileName, String filePath,HttpServletRequest request, HttpServletResponse response)
            throws Exception {}

方法如下:

package com.fh.util;import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 文件处理 创建人:BYL 创建时间:2014年12月23日*/
public class FileUtils {public static void filedown(String fileName, String filePath,HttpServletRequest request, HttpServletResponse response) {try {// 得到该文件File file = new File(filePath + fileName);if (!file.exists()) {System.out.println("Have no such file!");return;// 文件不存在就退出方法}FileInputStream fileInputStream = new FileInputStream(file);// 设置Http响应头告诉浏览器下载这个附件String userAgent = request.getHeader("User-Agent");// 针对IE或者以IE为内核的浏览器:if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {fileName = java.net.URLEncoder.encode(fileName, "UTF-8");} else {// 非IE浏览器的处理:fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", fileName));response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setCharacterEncoding("UTF-8");OutputStream outputStream = response.getOutputStream();byte[] bytes = new byte[2048];int len = 0;while ((len = fileInputStream.read(bytes)) > 0) {outputStream.write(bytes, 0, len);}fileInputStream.close();outputStream.close();} catch (Exception e) {// TODO: handle exception}}/*** 文件下载方法* @param fileName 文件名称(PZ_DEMO.zip)* @param filePath 文件路径(D://uploadFiles//PG//IMAGE//176d10329c29420e97fce1a39586a7b220190801091805//YX_zip_20190801091845856.zip)* @param request  * @param response*/public static void filedownShowEX(String fileName, String filePath,HttpServletRequest request, HttpServletResponse response)throws Exception {// 看到response中的usingWriter=true,随即想办法将该标志位设置为false;response.reset(),即可,注意reset后缓存消失,设置消失。response.reset();// 得到该文件File file = new File(filePath);FileInputStream fileInputStream = new FileInputStream(file);// 设置Http响应头告诉浏览器下载这个附件String userAgent = request.getHeader("User-Agent");// 针对IE或者以IE为内核的浏览器:if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {fileName = java.net.URLEncoder.encode(fileName, "UTF-8");} else {// 非IE浏览器的处理:fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");}response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", fileName));response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setCharacterEncoding("UTF-8");OutputStream outputStream = response.getOutputStream();byte[] bytes = new byte[2048];int len = 0;while ((len = fileInputStream.read(bytes)) > 0) {outputStream.write(bytes, 0, len);}fileInputStream.close();outputStream.close();}/*** txt文件编码判断* * @param filePath*            文件路径* @return (是:true(是:US-ASCII 编码) ;否:false(不是:US-ASCII 编码) )* @throws Exception*/// java编码 与 txt编码对应// java txt// unicode unicode big endian// utf-8 utf-8// utf-16 unicode// gb2312 ANSIpublic static boolean checkIsFileASCII(String filepath) throws Exception {File sourceFile = new File(filepath);String charset = "GB2312";byte[] first3Bytes = new byte[3];try {boolean checked = false;BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));bis.mark(0);int read = bis.read(first3Bytes, 0, 3);if (read == -1) {charset = "GB2312"; // 文件编码为 ANSI} else if (first3Bytes[0] == (byte) 0xFF&& first3Bytes[1] == (byte) 0xFE) {charset = "UTF-16LE"; // 文件编码为 Unicodechecked = true;} else if (first3Bytes[0] == (byte) 0xFE&& first3Bytes[1] == (byte) 0xFF) {charset = "UTF-16BE"; // 文件编码为 Unicode big endianchecked = true;} else if (first3Bytes[0] == (byte) 0xEF&& first3Bytes[1] == (byte) 0xBB&& first3Bytes[2] == (byte) 0xBF) {charset = "UTF-8"; // 文件编码为 UTF-8checked = true;}bis.reset();if (!checked) {int loc = 0;while ((read = bis.read()) != -1) {loc++;if (read >= 0xF0)break;if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBKbreak;if (0xC0 <= read && read <= 0xDF) {read = bis.read();if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)// (0x80// - 0xBF),也可能在GB编码内continue;elsebreak;} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小read = bis.read();if (0x80 <= read && read <= 0xBF) {read = bis.read();if (0x80 <= read && read <= 0xBF) {charset = "UTF-8";break;} elsebreak;} elsebreak;}}}bis.close();} catch (Exception e) {e.printStackTrace();}System.out.println("文件:" + filepath + "的编码格式为:" + charset);if (charset.equalsIgnoreCase("GB2312")) {return true;} else {return false;}}/*** 创建目录* * @param destDirName目标目录名* @return*/public static Boolean createDir(String destDirName) {File dir = new File(destDirName);if (!dir.getParentFile().exists()) { // 判断有没有父路径,就是判断文件整个路径是否存在return dir.getParentFile().mkdirs(); // 不存在就全部创建}return false;}/*** 删除文件* * @param filePathAndName*            String 文件路径及名称 如c:/fqf.txt* @param fileContent*            String* @return boolean*/public static void delFile(String filePathAndName) {try {String filePath = filePathAndName;filePath = filePath.toString();java.io.File myDelFile = new java.io.File(filePath);myDelFile.delete();} catch (Exception e) {System.out.println("删除文件操作出错");e.printStackTrace();}}/*** 读取到字节数组0* * @param filePath*            //路径* @throws IOException*/public static byte[] getContent(String filePath) throws IOException {File file = new File(filePath);long fileSize = file.length();if (fileSize > Integer.MAX_VALUE) {System.out.println("file too big...");return null;}FileInputStream fi = new FileInputStream(file);byte[] buffer = new byte[(int) fileSize];int offset = 0;int numRead = 0;while (offset < buffer.length&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {offset += numRead;}// 确保所有数据均被读取if (offset != buffer.length) {throw new IOException("Could not completely read file "+ file.getName());}fi.close();return buffer;}/*** 读取到字节数组1* * @param filePath* @return* @throws IOException*/public static byte[] toByteArray(String filePath) throws IOException {File f = new File(filePath);if (!f.exists()) {throw new FileNotFoundException(filePath);}ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());BufferedInputStream in = null;try {in = new BufferedInputStream(new FileInputStream(f));int buf_size = 1024;byte[] buffer = new byte[buf_size];int len = 0;while (-1 != (len = in.read(buffer, 0, buf_size))) {bos.write(buffer, 0, len);}return bos.toByteArray();} catch (IOException e) {e.printStackTrace();throw e;} finally {try {in.close();} catch (IOException e) {e.printStackTrace();}bos.close();}}/*** 读取到字节数组2* * @param filePath* @return* @throws IOException*/public static byte[] toByteArray2(String filePath) throws IOException {File f = new File(filePath);if (!f.exists()) {throw new FileNotFoundException(filePath);}FileChannel channel = null;FileInputStream fs = null;try {fs = new FileInputStream(f);channel = fs.getChannel();ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());while ((channel.read(byteBuffer)) > 0) {// do nothing// System.out.println("reading");}return byteBuffer.array();} catch (IOException e) {e.printStackTrace();throw e;} finally {try {channel.close();} catch (IOException e) {e.printStackTrace();}try {fs.close();} catch (IOException e) {e.printStackTrace();}}}/*** Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能* * @param filename* @return* @throws IOException*/public static byte[] toByteArray3(String filePath) throws IOException {FileChannel fc = null;RandomAccessFile rf = null;try {rf = new RandomAccessFile(filePath, "r");fc = rf.getChannel();MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,fc.size()).load();// System.out.println(byteBuffer.isLoaded());byte[] result = new byte[(int) fc.size()];if (byteBuffer.remaining() > 0) {// System.out.println("remain");byteBuffer.get(result, 0, byteBuffer.remaining());}return result;} catch (IOException e) {e.printStackTrace();throw e;} finally {try {rf.close();fc.close();} catch (IOException e) {e.printStackTrace();}}}/*** 写入文件* * @param filePath* @param content*/public static void contentToTxt(String filePath, String content) {String str = new String(); // 原有txt内容String s1 = new String();// 内容更新try {File f = new File(filePath);if (f.exists()) {System.out.print("文件内容写入时 文件存在");BufferedWriter output = new BufferedWriter(new FileWriter(f));output.write("");output.close();} else {System.out.print("文件内容写入时 文件不存在");f.createNewFile();// 不存在则创建}BufferedWriter output = new BufferedWriter(new FileWriter(f));output.write(content);output.close();} catch (Exception e) {e.printStackTrace();}}// 读取文件总行数public static int readFileLineNums(String filepath, String filename) {int x = 0;// 用于统计行数,从0开始try {FileReader fr = new FileReader(filepath); // 这里定义一个字符流的输入流的节点流,用于读取文件(一个字符一个字符的读取)BufferedReader br = new BufferedReader(fr); // 在定义好的流基础上套接一个处理流,用于更加效率的读取文件(一行一行的读取)while (br.readLine() != null) { // readLine()方法是按行读的,返回值是这行的内容x++; // 每读一行,则变量x累加1}br.close();fr.close();} catch (Exception e) {e.printStackTrace();}return x; // 返回总的行数}
}

java.lang.IllegalStateException: getWriter() has already been called for this response问题解决相关推荐

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

    简单的说:用了流之后关掉即可. 下面详细说明: 出现了java.lang.IllegalStateException: getOutputStream() has already been calle ...

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

    在做报表导出的时,导出报表后服务器提示: java.lang.IllegalStateException: getOutputStream() has already been called for ...

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

    文章目录 问题背景 分析 解决方案 错误信息详情: 严重: Servlet.service() for servlet [jsp] in context with path [/exportExcel ...

  4. java.lang.IllegalStateException: getOutputStream() has already been ca...

    tomcat正常启动. 但是一出来有验证码的页面,后台就会报错: 信息: Server startup in 13157 ms 2008-01-09 21:35:40,390 ERROR [org.a ...

  5. 转:java.lang.IllegalStateException异常产生的原因及解决办法

    地址:http://jorton468.blog.163.com/blog/static/72588135201102441617287/ 问题描述: 错误类型大致为以下几种: java.lang.I ...

  6. java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction. in /U

    错误内容如下 java.lang.IllegalStateException: Cannot modify managed objects outside of a write transaction ...

  7. 批量下载的实现及java.lang.IllegalStateException异常

    在工作流的一张表单里可能会有多个步骤上传附件,在用户的待办中往往会存在多条带有附件的任务,如果一一打开并且点击下载链接下载,不仅费时,而且繁琐,用户体验较差. OA系统采用的是FastDFS做为文件服 ...

  8. JDK8 stream toMap() java.lang.IllegalStateException: Duplicate key异常解决(key重复)

    测试又报bug啦 接到测试小伙伴的问题,说是一个接口不返回数据了,好吧,虽然不是我写的接口任务落到头上也得解决,本地调试了一下,好家伙,直接抛了个异常出来,这又是哪位大哥喝醉了写的代码... Exce ...

  9. 订阅者java_RxJava:“java.lang.IllegalStateException:只允许一个订阅者!”

    我正在使用RxJava来计算Android中某些传感器数据的标准化自动关联 . 奇怪的是,我的代码抛出一个异常("java.lang.IllegalStateException:只允许一个订 ...

最新文章

  1. Java - PriorityQueue
  2. 刚刚更新:在线聊天系统设计(原理+思路+源码+效果图)
  3. lazada发货_Lazada怎么发货?最全Lazada发货流程及注意事项!值得收藏!
  4. python的pillow给图片加文字_Python-Pillow库给图片添加文字、水印
  5. linux主机熵值过小,tomcat在linux启动应用慢解决方式
  6. 重庆计算机教师招聘 专业技能测试什么,教师招聘考试面试,专业技能测试考什么?全在这了...
  7. leetcode -- Search Insert Position
  8. linux apache gzip压缩,Linux入门教程:配置Apache开启gzip压缩传输,gzip压缩 LoadModul
  9. 9--Rails数据交互1
  10. zookeeper中ExpiryQueue详解
  11. linux字体不识别不了怎么办,Docker容器不识别宋体等字体的解决方案
  12. Kaggle Top1% 是如何炼成的!
  13. Mybatis操作Oracle中的Clob和Blob字段
  14. 《Drools7.0.0.Final规则引擎教程》第4章 global全局变量
  15. STM32寻迹智能车
  16. [手工设计]手工diy牡丹花
  17. 离散数学 —— 二元关系(图、零图与平凡图、度、握手定理、平行边、简单图与完全图、补图、子图与生成子图、同构、通路与回路、点与边割集、最短路线问题、强弱联通图、邻接矩阵与可达矩阵、欧拉图、平面图等)
  18. 阿里巴巴2019财年Q1财报:连续六季度高速增长,加码投资未来
  19. 防不胜防?网络钓鱼攻击常用手法盘点与防护建议
  20. 老子《道德经》第六十二章

热门文章

  1. 讲讲语言转换程序:将一种语言转换为另一种语言的程序
  2. android movie 资源释放,Android 资讯类App项目实战 第四章 电影模块
  3. BUUCTF做题小结
  4. 【C#】封装的复数运算类库及拓展到复数域的Math类
  5. 更新查询能用计算机,小黑盒怎么更新电脑配置 查成绩方法
  6. android alsa 命令,[zz]Android下使用alsa-utils调试ALSA驱动
  7. flask专题-小说网站开发二(抓取数据)
  8. 浮动练习之猫眼电影的电影页面
  9. 机器视觉_HALCON_快速向导_2.用HALCON开发程序
  10. React之官网首页篇