Getting the space available on a hard drive (partition)

I’m working on a tutorial for a client involving file uploads (which I’ll be sharing on the blog). In the tutorial I talk a bit about monitoring the number of uploads and how much space they are taking. I was curious what methods exist for finding out how much space is being used on a drive and how much space is available. Finding out the space used by a directory is possible with CFDIRECTORY and query of query:

<cfdirectory directory="#expandPath('.')#" recurse="true" action="list" name="allfiles">

<cfquery name=”getSize” dbtype=”query”> select sum(size) as total from allfiles </cfquery>

<cfoutput>Total size in bytes is: #getSize.total#</cfoutput> </code>

While this works it doesn’t tell me how much space is available - just how much space a folder (and it’s children) are using. I looked into the Java API and discovered that in version 6 methods were added to java.io.File just for this purpose. (What I find funny is that it apparently took 9 years for the feature to be added. I wonder why?)

You have 2 main methods you can use - java.io.File.getFreeSpace and java.io.File.getUsableSpace. The docs explain that getUsableSpace is a bit safer than getFreeSpace:

Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().

You also have available getTotalSpace, which returns the complete size of the partition. Here is a simple example of these functions:

<cfset fileOb = createObject("java", "java.io.File").init("/")> <cfoutput> freespace=#fileOb.getFreeSpace()#<br> usablespace=#fileOb.getUsableSpace()#<br> totalspace=#fileOb.getTotalSpace()#<br> </cfoutput>

Obviously “/” as a path is only going to work on Linux/OSX. (Well, I assume it won’t work in Windows. If I’m wrong, let me know.)

p.s. This blog entry was written 3 hours ago. I was about one sentence away from being done when there was a large boom and the house went dark. Our electrical network on this street is made of swiss cheese. Thankfully I had the UPS running so I was able to quickly shutdown. I went over to my local CCs (coffee house) and used the wireless there. Since my mail was all stored on Google I didn’t have much downtime. The power is back on… for now.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments