API to create a temp file for the duration of task execution

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

API to create a temp file for the duration of task execution

Al Le
Hello,

I'd like to implement a custom task. Its implementation would perform
following things:

1. Create a file (in .properties format)

2. Do some magic (the main logic of the task) which uses the file
created in step 1.

3. Delete the file created in step 1.

You see that the file from the step 1 is just a temporary one and should
not remain after the task is completed.



I have some questions:

1. Is there an Ant API to create a temp file? Or should I just use the
standard Java API for this?

2. How would I ensure that the file is deleted after the task completes?
Is there some mechanisms for this is Ant? Or should I just carefully
program try-catch-finally and delete the file in the finally block (or
use try with resources)?

Thank you for any hints.

AL

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]

Reply | Threaded
Open this post in threaded view
|

Re: API to create a temp file for the duration of task execution

Stefan Bodewig
On 2018-02-18, Al Le wrote:

> 1. Is there an Ant API to create a temp file? Or should I just use the
> standard Java API for this?

There is FileUtils.createTempFile which of course uses the standard Java
API under the covers, but allows you to specify whether the file should
actually be created and whether it should be deleted on VM exit in a
single method invocation.


> 2. How would I ensure that the file is deleted after the task
> completes? Is there some mechanisms for this is Ant? Or should I just
> carefully program try-catch-finally and delete the file in the finally
> block (or use try with resources)?

Use deleteOnExit as a safety net in addition to a finally block.

If you plan to see your task running on Windows, be extra careful to
check the return value of File.delete - or better, yet, use
FileUtils.tryHardToDelete and check the return value. Sometimes the JVM
simply doesn't seem to be able to remove files it has created soonish
after all streams have been closed on Windows.

Stefan

---------------------------------------------------------------------
To unsubscribe, e-mail: [hidden email]
For additional commands, e-mail: [hidden email]