Another CFML w/ Java Trick

I just wrote a script that would check for orphaned files in an
uploads directory.  Orphan meaning the file still exists, but the
database doesn't have record of it.  Those files needed to either
be reclaimed or deleted, but finding them is cumbersome (and slow!)
process.

What I discovered is that CFDIRECTORY ACTION="list" is really slow if you just need a list of filenames without any of the extra metadata.  Using the list() method of the java.io.File
class turned out to be more than a order of magnitude faster.  The
one caveat is that you can't do a filter without writing some Java (an
implementation of java.io.FileFilter or java.io.FilenameFilter).  But for the performance gain, it's hard to beat.

Here's the CFML code:

<cfdirectory action="list" directory="#LOCAL_DIRECTORY#" name="files" />

And here's the Java code:

<cfset fileList = createObject("java", "java.util.Arrays").asList(
createObject("java", "java.io.File").init(LOCAL_DIRECTORY).list()
) />

With the Java, you get an instance of java.util.List, which can be treated just like a normal CF array.

2 responses to “Another CFML w/ Java Trick”

  1. David Rubin

    Hi there! We're using your example and would like to bother you with a question… how can you add a bit of functionality to this java object making the list in order to have it filter the list based on a wildcard string, such as 12*.jpg? We're having difficulty finding a succinct solution.

  2. Barney

    If you want to filter, you'll need to use a java.io.FileFilter implementation. That means you actually have to write a Java class, compile it, and add it to your classpath.