有没有关闭现有的FileInputStream删除? [英] is there an existing FileInputStream delete on close?

查看:194
本文介绍了有没有关闭现有的FileInputStream删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以让 FileInputStream 在关闭时自动删除底层文件?



我打算让自己的实用程序类扩展 FileInputStream 并自己做,但我有点儿惊讶的是没有东西已经存在。

edit:用例是我有一个返回 InputStream 从一个页面下载文件。据我所知,当动作完成时,我不会收到通知,或者 FileInputStream 不再被使用,而且我不希望大)的临时文件,生成要下载左转。



这个问题不是Struts 2的具体问题,所以我原来并没有包含这些信息,问题。

解决方案

标准库中没有这样的东西,也没有任何的apache-commons库,所以像:

  public class DeleteOnCloseFileInputStream扩展FileInputStream {
private文件文件;
public DeleteOnCloseFileInputStream(String fileName)抛出FileNotFoundException {
this(new File(fileName));

public DeleteOnCloseFileInputStream(File file)throws FileNotFoundException {
super(file);
this.file = file;

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


Is there an existing way to have a FileInputStream delete the underlying file automatically when closed?

I was planning to make my own utility class to extend FileInputStreamand do it myself, but I'm kinda surprised that there isn't something already existing.

edit: Use case is that I have a Struts 2 action that returns an InputStream for file download from a page. As far as I can tell, I don't get notified when the action is finished, or the FileInputStream is not in use anymore, and I don't want the (potentially large) temporary files that are generated to be downloaded left lying around.

The question wasn't Struts 2 specific, so I didn't include that info originally and complicate the question.

解决方案

There's no such thing in the standard libraries, and not any of the apache-commons libs either , so something like:

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;
         }
       }
   }
}

这篇关于有没有关闭现有的FileInputStream删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆