Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically Delete Temporary Files using "new" Java File API

After years of coding with the old File API, I'm finally ready to hop onto the whole Path/Paths train. For the most part, this has gone smoothly, however, I'm stumped on this particular aspect: temporary files.

The documentation on java.nio.Files#createTempFile says:

As with the File.createTempFile methods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically.

I don't see where the DELETE_ON_CLOSE option is supposed to be specified. Using a shutdown hook is incredibly inconvenient (unless I'm thinking of it wrong). In an effort to avoid using both Path objects and File objects, I am looking for a solution similar to the File.deleteOnExit() for the Path object, but obviously one that doesn't require using Path.toFile().[...].toPath() sort of calling pattern.

What is the correct way to implement "self-destructing" temporary files using the java.nio.Files API?


1 Answers

You set that option when you write, for example:

Path myTempFile = Files.createTempFile(...);
Files.write(myTempFile, ..., StandardOpenOption.DELETE_ON_CLOSE);
like image 130
martinez314 Avatar answered Oct 28 '25 22:10

martinez314