Java读取文件后文件被占用

Java读取文件响应后文件一直被占用问题

原因:

  由于是封装的函数,请求和响应对象都是 形参地址

  虽然在此函数里关闭了输出流,但是由于有返回值,调用未结束,输出流无法提前关闭

解决:

  1:调用函数后,在外部函数再次关闭响应流

  2:封装函数写成无返回值格式

代码:

问题代码:

// 读取文件
public boolean requestFile(File file, HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = null;// Servlet输出流
    FileInputStream ips = null;// 文件输入流
    try {
        String fileName = file.getName();
        // 文件名编码
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        // 设置响应头,控制浏览器下载该文件
        response.setContentType(Utils.getFileType(fileName));// 描述消息内容类型
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.setContentLengthLong(file.length());
        ips = new FileInputStream(file);
        out = response.getOutputStream();
        // 读取文件流
        int len = 0;
        byte[] buffer = new byte[1024 * 10];
        while ((len = ips.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    } catch (Exception e) {
    return false; }
finally { if (out != null) out.close(); if (ips != null) ips.close(); }
  return true; }

正确代码:

// 读取文件
public void requestFile(File file, HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = null;// Servlet输出流
    FileInputStream ips = null;// 文件输入流
    try {
        String fileName = file.getName();
        // 文件名编码
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        // 设置响应头,控制浏览器下载该文件
        response.setContentType(Utils.getFileType(fileName));// 描述消息内容类型
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.setContentLengthLong(file.length());
        ips = new FileInputStream(file);
        out = response.getOutputStream();
        // 读取文件流
        int len = 0;
        byte[] buffer = new byte[1024 * 10];
        while ((len = ips.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    } catch (Exception e) {
    } finally {
        if (out != null)
            out.close();
        if (ips != null)
            ips.close();
    }
}

 

以上为个人总结,欢迎斧正

posted @ 2022-05-31 23:32  散人长情  阅读(771)  评论(0编辑  收藏  举报