is there an existing FileInputStream delete on close?

江枫思渺然 提交于 2019-11-29 01:14:35

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

I know this is a fairly old question; however, it's one of the first results in Google, and Java 7+ has this functionality built in:

Path path = Paths.get(filePath);
InputStream fileStream = Files.newInputStream(path, StandardOpenOption.DELETE_ON_CLOSE);

There are a couple caveats with this approach though, they're written up here, but the gist is that the implementation makes a best effort attempt to delete the file when the input stream is closed, and if that fails makes another best effort attempt when the JVM terminates. It is intended for use with temp files that are used solely by a single instance of the JVM. If the application is security sensitive, there are also a few other caveats.

Can you can use File.deleteOnExit() before opening the file ?

EDIT: On you can subclass a FileInputStream that will delete the file on 'close()';

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

I know this is an old question, but I just ran into this issue, and found another answer: javax.ws.rs.core.StreamingOutput.

Here's how I used it:

    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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!