Site iconJava PDF Blog

Two issues with Java File access for temporary files

In theory, Java has a very flexible and powerful set of commands for manipulating Files. The File object allows you create a File or Directory, access alsorts of information about it and also delete it. The problem we find, however, is that it is not always possible to delete a file in Java by using file.delete(), even if you created it. Especially on Windows, Java retains a lock on the files and will not delete the file in the session – even if you created it. This can be a real issue if you create lots of temporary files which need to be cleaned up. You can create a File with a deleteOnExit() call, but if the program is expected to run continually, this will create a memory leak and not ever delete the files.

So we added a work around, checking in the next session for old files and deleting them so keep our temp directory clean. This exposes a second issue – the lastModified() method seems to be incredibly inefficient. In our tests, on systems with lots of files, this function alone was accounting for 30% of the CPU usage in a process which opened PDFs decoded them, rasterized them and then deleted them. 

So if you are using File commands for temporary files, be careful to ensure they are deleted, and try to have small numbers of files if you need to access their timestamp.