Ever work with <cfdirectory> or <cfzip> and notice that they both ignore empty directories? This might make sense with some business logic, where an empty directory can (and should) be ignored. However, what if you want to ensure that empty directories are included in a zip file?

Our first iteration involved using to list the directories, loop over all directories, and determine if there are files within each directory. If a directory is empty, we place a placeholder.txt empty file in the directory. Here is what the code looked like:

?View Code COLDFUSION
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<cffunction name="_addPlaceholderFileToEmptyDirs" access="private" returntype="void">
	<cfargument name="file" required="false" default="#variables.pathToCourse#\ClassFiles">
	<cfset var dir = ''>
	<cfset var subdir = ''>
	<cfdirectory action="list" directory="#pathToClassFilesDir#" name="dir" recurse="true" type="dir">
	<ol>
		<cfloop query="dir">
			<cfif not ListFindNoCase('props,prop-base,text-base,.svn', dir.name)>
				<cfdirectory action="list" directory="#dir.directory#" name="subdir">
				<cfif not subdir.recordcount>
					<cffile action="copy" source="#variables.dirWCWC#\placeHolder.txt" destination="#dir.Directory#\placeholder.txt">
					<cfoutput><li>#Directory#\placeHolder.txt.</li></cfoutput>
				</cfif>
			</cfif>
		</cfloop>
	</ol>
</cffunction>

After (not so) quickly realizing that is ignoring empty directories we moved to a second iteration. This time, we used Java to get the list of directories, and recursively copy the placeholder file into empty directories. Here is the code:

?View Code COLDFUSION
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<cffunction name="_addPlaceholderFileToEmptyDirs" access="private" returntype="void">
	<cfargument name="dirpath" required="false" type="string" default="#variables.pathToCourse#\ClassFiles">
	<cfset var directory = CreateObject("java", "java.io.File").init(dirpath)>
	<cfset var files = directory.listFiles()>
	<cfset var i = 0>
	<cfloop from="1" to="#ArrayLen(files)#" index="i">
		<cfif files[i].isDirectory() AND ArrayLen(files[i].listFiles())>
			<cfset _addPlaceholderFileToEmptyDirs(files[i].getAbsolutePath())>
		<cfelseif files[i].isDirectory()>
			<cffile action="copy" source="#variables.dirWCWC#\placeHolder.txt" destination="#files[i].getAbsolutePath()#\placeholder.txt">
			<cfoutput><li>Placeholder added to: #files[i].getName()#</li></cfoutput>
		</cfif>
	</cfloop>
	</ol>
</cffunction>
This entry was posted on Tuesday, June 2nd, 2009 at 1:56 pm.
Categories: Adobe, ColdFusion, ColdFusion 8, Java.

One Comment, Comment or Ping

  1. Adam Cameron

    G’day
    CFDIRECTORY sure doesn’t skip empty directories for me.

    Are you sure something else you’re not expecting isn’t at play here?


    Adam

Reply to “Empty directories with cfdirectory and cfzip”