I have to store an image for a few minutes after user upload it until user confirm and i store in database
So i'm wondering of creating a temporary file and use it to display preview.
But I have to be sure that the file will be deleted after some time if user not interact anymore
I found this article about temporary files and how delete them automatically https://softwarecave.org/2014/02/05/create-temporary-files-and-directories-using-java-nio2/
But if I understood right, deleteOnExit and ShutdownHook will call after vm shutdown, so if my application stays online for a long time thanks, these files never be deleted and DELETE_ON_EXIT option will delete file when i call the close method, so if I never call cause user dont do nothing, the file never be deleted as well. That's right?
So.. Has any way to garantee the file will be deleted after automatically some time?
I'm thinking to create a File with deleteOnExit and DELETE_ON_CLOSE option, and add to a thread with "timeout", and after this timeout check if file still exist and delete, but i don't know if exist best approach.
Thanks
UPDATE
Based on best answer i develop a project to add this behavior on java.util.File
write in Kotlin.
https://github.com/vinicius-rob-cunha/kotlin-auto-delete-file