Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Two issues with Java File access for temporary files

51 sec read

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.



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.