5

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

2 Answers 2

5

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
        }
    }
}
5
  • I really like this approach, I didn't know about these executors. Just one question, seems that Timer do the work too, but what differences between both of them? Commented Apr 19, 2017 at 2:55
  • @ViniciusCunha Check stackoverflow.com/questions/409932/… for a description
    – dev4Fun
    Commented Apr 19, 2017 at 4:17
  • thanks for the answer and explanation, i'll use thie with SingleThread, since i just need to delete files. Commented Apr 19, 2017 at 14:24
  • getDelay returning the remaing time so, this reschedule doesn't work Commented Apr 19, 2017 at 19:34
  • thanks, based on your answer i develop a project in Kotlin to add this funcionality to java.util.File github.com/vinicius-rob-cunha/kotlin-auto-delete-file Commented Apr 19, 2017 at 22:30
0

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.

1
  • You're right in using Timer() is better option refer by TIMER VS THREAD But it is better only in readability and cancel() is implemented. Anyhow Thank you for the comment. Commented Apr 19, 2017 at 3:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.