CF Quick Tip: Checking available free space with Java io.File

CF Quick Tip: Checking available free space with Java io.File

Note: This article originally appeared on tedparton.com on 02/26/2013

Earlier today I noticed on Ray Camden’s site a blog post about determining the amount of free space on a drive from ColdFusion. It looks like in CF10, a new function, getFreeSpace(‘path’) was added that will return the amount of free space in MB back.
Here’s the article: http://www.raymondcamden.com/index.cfm/2013/1/22/Using-ColdFusion-to-check-available-disk-space

For those of us not yet on ColdFusion 10, the following article outlines how you can drill down to the Java File class to get the free space. http://www.jozza.net/blog/measuring-disk-space-in-coldfusion/141/

In particular, pay attention to the second part, because with the .init() outlined, you can pass in an exact path. This can be handy with AWS, local file shares, etc.

So if you aren’t on CF10 yet, you could put together your own custom CFC, to return the amount of free space, something as simple as:

First let’s create a custom function to check the free space:

<cffunction name="getFreeSpace" displayname="getFreeSpace" description="Use Java.io.File to return amount of free space in target path" access="public" output="false" returntype="any">
   <cfargument name="path" displayName="path" type="string" hint="File path" required="true" />

   <!--- Create an instance of the Java IO File Class --->
   <cfset var objFile = createObject("java", "java.io.File").init(arguments.path)/>

   <!--- Return the amount of free space --->
   <cfreturn objFile.getFreeSpace() />
</cffunction>	<!--- End: checkFreeSpace() --->

With the function above, you can run a simple test case such as…

<cfset variables.structTest = structNew()/>
<!--- Determine the current file path --->
<cfset variables.structTest.current_folder = expandPath("/") />

<!--- Lookup free space based on the passed in file path --->
<cfset variables.structTest.freeSpace = numberFormat(getFreeSpace(variables.structTest.current_folder)) />

<cfdump var="#variables.structTest#" label="structTest" />

Your dump should look something like this: