How to remove the file after the download if finished?

I would like to use FileDownloader to download the file which is generated dynamically. Now it works and the file could be downloaded. But I want to delete the file after the download is finished.

How can I do this?

Any suggestion would be appreciated.

Thanks in advance.

That’s a tricky one. The only way I see that might work is extending the underlying InputStream and overriding the close() method. E.g. The FileResource class returns an InputStream, so you’d need to extend that as well (or whatever resource you are using).

But there is another way. In most cases you don’t need to create a file at all. If you have the byte content of the file, you should use a StreamResource instead; this one doesn’t create files and is much better for performance. Of course, this only works if you generate the file with tools inside the JVM.