前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >程序员最基本的素养是什么?关闭流!

程序员最基本的素养是什么?关闭流!

作者头像
周杰伦本人
发布2022-10-25 15:26:27
1820
发布2022-10-25 15:26:27
举报
文章被收录于专栏:同步文章

今天发现一个压缩包文件总是删不掉 在windows下也删不掉。。

原因是:inputStream流忘了关了。。

代码语言:javascript
复制
/**
     * 从浏览器下载压缩文件
     * @param file
     * @param response
     * @param isDelete
     * @throws IOException 
     */
    public static void downloadZipFile(File file,HttpServletResponse response,boolean isDelete) throws IOException{
    	BufferedInputStream fis = null;
    	OutputStream toClient = null;
		InputStream inputStream = null;
    	 try {
            
             // 清空response
             response.reset();
             toClient = new BufferedOutputStream(response.getOutputStream());
             response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
	           
             response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
			 inputStream=new FileInputStream(file);
			 int len=0;
			 byte[] buffer=new byte[1024];
			 while((len=inputStream.read(buffer))>0){
				 toClient.write(buffer,0,len);
			 }
             toClient.flush();
          catch (IOException ex) {
              logger.error(ex.getMessage());
         }finally{
        	 if(fis!=null){
        		 fis.close();
        	 }
        	 if(toClient!= null){
        		 toClient.close();
        	 }
			 if(inputStream!= null){
				 inputStream.close();
			 }

         }
    	 //在所有流都关闭后再删除文件
        if(isDelete) {//是否将生成的服务器端文件删除
            if (file.exists()) {
                if (!file.delete()){
                    logger.error("删除失败");
                }
            }

        }
	}

IO操作关闭流,是做程序员的最基本素质。

参考博客: https://blog.csdn.net/keep12moving/article/details/89386058

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-12-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档