2011-01-14 33 views
19

是否有一种方法让FileInputStream在关闭时自动删除底层文件?有没有关闭现有的FileInputStream删除?

我打算让自己的实用课程延长FileInputStream并自己做,但我有点惊讶,有没有已经存在的东西。

编辑:用例是我有一个Struts 2操作,返回一个InputStream用于从页面下载文件。据我所知,当动作完成时我没有得到通知,或者FileInputStream没有被使用,我也不希望生成的(可能很大的)临时文件被下载到左边。

问题不是Struts 2的具体问题,所以我最初没有包含这些信息,并且使问题复杂化。

+0

有什么用例为这个? – skaffman 2011-01-14 17:28:33

+2

@skaffman相当明显,读完文件后他想删除它(詹姆斯邦德式,这个磁带会在这封邮件后自行破坏) – 2011-01-14 17:30:21

+1

@Sean:这不是一个用例。用例就是他刚刚添加到问题中的东西。 – skaffman 2011-01-14 17:35:53

回答

25

有没有这样的事情在标准库,并没有任何的Apache的公共库的任何,所以像:

public class DeleteOnCloseFileInputStream extends FileInputStream { 
    private File file; 
    public DeleteOnCloseFileInputStream(String fileName) throws FileNotFoundException{ 
     this(new File(fileName)); 
    } 
    public DeleteOnCloseFileInputStream(File file) throws FileNotFoundException{ 
     super(file); 
     this.file = file; 
    } 

    public void close() throws IOException { 
     try { 
      super.close(); 
     } finally { 
      if(file != null) { 
      file.delete(); 
      file = null; 
     } 
     } 
    } 
} 
6

打开文件之前可以使用File.deleteOnExit()吗?

编辑:你可以继承一个FileInputStream,它将删除'close()'上的文件;

class MyFileInputStream extends FileInputStream 
{ 
File file; 
MyFileInputStream(File file) { super(file); this.file=file;} 
public void close() { super.close(); file.delete();} 
} 
3

我知道这是一个老问题,但我只是跑进入这个问题,并找到另一个答案:javax.ws.rs.core.StreamingOutput。

下面是我如何使用它:

File downloadFile = ...figure out what file to download... 
    StreamingOutput so = new StreamingOutput(){ 
     public void write(OutputStream os) throws IOException { 
      FileUtils.copyFile(downloadFile, os); 
      downloadFile.delete(); 
    } 

    ResponseBuilder response = Response.ok(so, mimeType); 
    response.header("Content-Disposition", "attachment; filename=\""+downloadFile.getName()+"\""); 
    result = response.build();