is there an existing FileInputStream delete on close?

前端 未结 4 951
夕颜
夕颜 2020-12-15 16:52

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 t

4条回答
  •  伪装坚强ぢ
    2020-12-15 17:42

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

提交回复
热议问题