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

Note: This article originally appeared on 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:

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.

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 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", "").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:

Related Posts