This morning my day was kicked off with a warning from OS X that I had next to no space left on my hard drive and that I’d better clean stuff up pronto. Luckily, I knew exactly what to remove and I took care of it. However, while cleaning up files I stumbled across a set of files in my home directory with names like “c:/temp924A8A06-FE9F-462A-F4BDCA63C95797CE”. Now that’s an odd name for a file on a Mac!. I opened one of these files to see a barcode image and realized what was going on.
One of my client’s developers had been working on creating these barcode images and must have hard coded the creation of the images to their “c:temp” directory on Windows. My experience highlights one reason why this might not be the best way to create temp files: The directory might not exist! Or, it’s conceivable that the non-standard c:temp directory might not exist. Or that ColdFusion might not have rights to write to that directory. Or the application might be running on a non-Windows system like OS X, Linux or Unix.
So, with that in mind, what is the best way to create a temporary file in ColdFusion? This is a fairly easy problem to solve with two built in ColdFusion functions, GetTempDirectory and GetTempFile.
The GetTempDirectory function simply returns the path to a temporary directory that exists and ColdFusion can write to.
The GetTempFile creates a file in a specified path with a prefix.
Using these two functions together you can safely create a temporary file. This is the example from the ColdFusion documentation:
<h3>GetTempFile Example</h3> <p>The temporary directory for this ColdFusion Server is <cfoutput>#GetTempDirectory()#</cfoutput>.</p> <p>We have created a temporary file called: <cfoutput>#GetTempFile(GetTempDirectory(),"testFile")#</cfoutput></p>
One other point related to this, no mater what platform you’re running on, you should always use a front slash as your path separator and not a back slash. Java will automatically translate this to the correct separator for the platform your application runs on.