StructureCMS

December 2, 2009

Measuring disk space in Coldfusion

Filed under: ColdFusion — joel.cass @ 2:15 pm

If you’re supporting any legacy applications, then it’s probably only a matter of time until you will get that call early in the morning… “Hi, this is technical support, your server’s down. It seems to have run out of space on drive X…”.

This could have easily been avoided if you had set up some sort of alert. The should be easy right, as easy as using a cfdirectory tag… Oh wait, hold on, other than a recursive listing and summary being extremely inefficient, cfdirectory doesn’t tell you how much space is left on your drive.

Well, we’re all lucky that ColdFusion is built on top of Java. As it turns out, since JDK 6.0 Java has exposed drive information via the java.io.File library.

For example, if you wanted to get a list of all drives on the server, you could use the method File.listRoots():

<cfset objFile = createObject("java","java.io.File")>
<cfset aryRoots = objFile.listRoots()>

<cfset lstDrives = "">

<cfloop from="1" to="#arrayLen(aryRoots)#" index="i">
    <cfset lstDrives = listAppend(lstDrives, aryRoots[i].getPath())>
</cfloop>

Dumping out #lstDrives# would return something like “A:\,C:\,D:\” etc.

From that, you can then get the amount of space available:

<cfset objFile = createObject("java","java.io.File").init("C:\")>

<cfset stcReturn = structNew()>
<cfset stcReturn.freeSpace = objFile.getFreeSpace()>
<cfset stcReturn.totalSpace = objFile.getTotalSpace()>
<cfset stcReturn.readAccess = objFile.canRead()>
<cfset stcReturn.writeAccess = objFile.canWrite()>

If you wanted to set up an alert, you could use the readAccess / writeAccess flags to determine whether the drive should be checked. Chances are that if a drive cannot be read or written it is most probably a CD drive or an external media drive that is empty.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment