问题
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
回答1:
I don't think the approach with using jmv shutdown hooks is reliable and it seems not what you are looking for. I would suggest creating a class with map of files you want to schedule for deletion and have a callback that will allow to postpone deletion time when called:
private Map<Path, ScheduledFuture> futures = new HashMap<>();
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
private static final TimeUnit UNITS = TimeUnit.SECONDS; // your time unit
public void scheduleForDeletion(Path path, long delay) {
ScheduledFuture future = executor.schedule(() -> {
try {
Files.delete(path);
} catch (IOException e) {
// failed to delete
}
}, delay, UNITS);
futures.put(path, future);
}
public void onFileAccess(Path path) {
ScheduledFuture future = futures.get(path);
if (future != null) {
boolean result = future.cancel(false);
if (result) {
// reschedule the task
futures.remove(path);
scheduleForDeletion(path, future.getDelay(UNITS));
} else {
// too late, task was already running
}
}
}
回答2:
You can use Timer() class. It basically allows you to specify a Timer with a certain delay and a TimerTask. Timer executes the TimerTask after the delay is up and runs your code. You just have to set the file path for the TimerTask programmaticaly.
Here's Timer documentation.
来源:https://stackoverflow.com/questions/43483750/how-guarantee-the-file-will-be-deleted-after-automatically-some-time