Creating and managing temporary files in a Java application can be a little tricky due to some open JVM bugs. Develop a workaround with some custom code and a clever design.

WEBINAR:

On-Demand

was always taught to leave a place cleaner than when I got there, and I hold my applications to the same standard. However, a recent Java project I worked on was doing just the opposite, dumping temporary files on the user's system and never cleaning them up. Fearing the inevitable tech support call after the application filled the user's hard disk, I had to fix the problem.

The scenario was simple enough: like many applications, mine had to create temporary files on the user's system during its execution and it then—in theory—would clean them up at exit. The requirement for temporary files (short-lived files normally created in a designated temporary directory) varies from project to project. Applications requiring large batch processing may use temporary files as an intermediate step, while other apps use them to buffer input and output (I/O) from a network or a device. In my case, the temporary files, commonly called temp files, were actually Java Archives (JARs) created at runtime and loaded dynamically into the application (which I later found exasperated the situation). As the project deadline approached, I had to find the problem and, more importantly, develop a solution.

Due to two open Java bugs, a Java application that utilizes a combination of the JVM design and the Win32 operating system does not allow temp files to be deleted if they are open at exit. As a result, the application dumps temporary files on the user's system and never cleans them up.

The JVM can perform a quick cleanup step at startup to delete any temporary files that are lying around from the application's previous run. However, because the temp files must be marked as locked when they are created, put all of the temp files for a given instance of the application into a single directory and lock the directory.