今天发现一个压缩包文件总是删不掉 在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