Two Guys Arguing

Temp Files = No More Dumb Commits

Posted in Uncategorized by benjaminplee on 03.26.09

While writing a simple utility API used to modify Excel documents I ran into an annoying situation.  My end-to-end integration test was loading a test file, making a modification, verifying that the file was changed, and reversing the modification.  This worked great except that each time I ran the tests (all the time), the file’s timestamp would be changed.  This meant that every time I wanted to commit back to SVN, the file showed up as modified.

After noticing that this simple test file had a few dozen commits associated with it without any real change in values … I needed to find a better solution to setting-up and tearing-down my test data.

Enter File.createTempFile().  While surfing the always helpful Java Almanac I found a nice little tip to on how to create a temporary file in the system’s default temp directory.  According to the javadoc, the method will create a new empty file in the sytem’s default temp directory with a given prefix and file extension.  After the chosen prefix, the utility will generate a new random code.  This combined with File.deleteOnExit() allowed me to have my tests execute against a new file each time that is automatically cleaned up when the JVM closes which saves my commit logs.

It might not be perfect as a long term solution, but for now, it perfectly solved my problem.