当前位置:编程学习 > JAVA >>

struts2 打包下载后,怎么删除临时打包好的文件?


/*------------压缩--------------*/
public void baleZip() throws IOException{
String zipPath = ServletActionContext.getServletContext().getRealPath("/temp/");
File  zFile = new File(zipPath,"download.zip");
     if(!zFile.getParentFile().exists())
zFile.getParentFile().mkdirs();

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zFile));

for (int i = 0; i < names.length; i++) {

out.putNextEntry(new org.apache.tools.zip.ZipEntry(names[i]));
out.setEncoding("GBK");
InputStream in = ServletActionContext.getServletContext()
.getResourceAsStream("/download/" + names[i]);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.closeEntry();
in.close();
}
out.flush();
out.close();
}



public  InputStream getInputStream() throws IOException{
String path = ServletActionContext.getServletContext().getRealPath("/temp/");
File tempFile;
InputStream in;
tempFile = new File(path,"download.zip");
try {
baleZip();
in = new FileInputStream(tempFile);
} catch (IOException e) {
System.out.println(e.getMessage()+"   "+"压缩文件出错!!");
e.printStackTrace();
return null;
}finally{  if(tempFile.exists()){
        tempFile.delete();      //这里每次删除文件都失败
            if(tempFile.exists()){
                System.out.println("------删除临时文件失败-------");
            }else{
                System.out.println("------删除打包产生的临时文件------");
            }
        }
    }
return in;
}


这是按照网上的例子做出来的,压缩,下载做出来了,但是下载后就删除不了压缩好的文件了。
是 这里的“InputStream in;” 没有 close();吗? 但结果是要return in; 的。。。  
--------------------编程问答-------------------- 应该是流没有close的原因。
要返回的话,可以写先把流close掉,这时临时文件就删掉了。然后再打开一个流读出文件,然后返回这个新的流。这样怎么样? --------------------编程问答-------------------- 文件都删除了,怎么再打开一个流。。。? --------------------编程问答-------------------- --------------------编程问答-------------------- 怎么都没人回答了。 --------------------编程问答-------------------- 楼主 现在解决了吗?  教下我啊。。。。。。。。 --------------------编程问答-------------------- 用拦截器,action执行完毕后做删除处理 --------------------编程问答-------------------- 这是我的下载,红色部分是输出完了就直接删除掉
补充:Java ,  Web 开发
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,