Using Java instead of CFFILE and CFDIRECTORY

There are several reasons why jusing Java in place of CFFILE of CFDIRECTORY might be a good idea.  In many cases such as shared hosting environments, hosts block use of those tags.  While it obviously goes against the spirit of their intent of doing this, sometimes applications just need that functionality and this becomes a real roadblock for developers.

Secondly and in my opinion a very important reason is for performance.  Jusing Java to perform these tasks can be 10-20 times faster than using tag calls.  Fellow CF’er Phillip Holmes offers this reason: The reason why the Java example is much faster is because when you call the cffile tag, you’re actually calling a class that groups Java functionality together. This class is located in the lib/cfusion.jar file. By using the call to the Java.io namespace, you’re bypassing the excess functionality and error checking that CFMX does for you. So, you’re streamlining your operation by not instantiating code that you don’t use.

Reading a directory:
First let’s read a directory.  One thing that is worthy of mention is that this method will return an array rather than a ColdFusion query object, so this might not be just a plug-n-play change to code that has existing cfdirectory calls.  You will likely have to change the way you are accessing the returned data.  So, how do you do it?

<cfscript>
ourDirectory = expandPath(“./”);
directoryList = createObject(“java”,”java.io.File”).init(ourDirectory).list();
</cfscript>

This is obviously a bit more code to have to type out, so you may want to keep a UDF available that returns your array when a directory is passed to it.

Writing a file:
Trevor Burnette has given a great example of how to write files with using Java instead of CFFILE. I have tried this and found tremendous performance gains using his method. Go check out his blog for some good info.