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.


3 Responses

Subscribe to comments with RSS.

  1. BrianTheSmith said, on 03.27.09 at 7:53 am

    We use the File.createTempFile method all the time when testing Eclipse Plugins. We end up loading lots of files from plugins in our tests.

    so we end up doing something like this (using some Util classes from apache commons io)

    InputStream stream = getClass().getResourceAsStream(“resourcePathHere”);
    String streamContents = IOUtils.toString(stream);
    File temp = File.createTempFile(“IAlwaysUseTheTestMethodName”, “tmp”);

    //Do Something with the file

    • BrianTheSmith said, on 03.27.09 at 7:55 am

      oops that should be


      I should have looked at the JavaDocs first :p

    • benjaminplee said, on 03.27.09 at 8:27 am

      Its good to hear that I am not the only one and I really like your idea of using the test name as the file prefix. That should be helpful in tracing any problems if they come up.

      Also, I am assuming you meant FileUtils.writeStringToFile(temp, streamContents); ;-)

      Thanks for the comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s