Deleting a file when using java.io.FileReader
Posted on August 2, 2007
A problem was posted to CF-Talk about CF locking a file when using java.io.FileReader. You may run into the same problem when parsing files using CF 6 or 7. Fortunately, Coldfusion 8 (Scorpio) has eliminated the process of calling java directly by updating CFLOOP.
The problem
When dealing with large text files (i.e. CSV), CFFILE can take its sweet time, chewing up memory as it reads an entire file before trying to parse it. For example, a client of mine has an inventory import file that is usually around 70Mb in size. Using CFFILE, The process of reading, parsing and importing the CSV file into the database usually took more than 40 minutes.
The Java solution
Thankfully, we can use java.io.FileReader and java.io.BufferedReader to alleviate this problem. Jeffry Houser wrote a great article about them inthe CFDJ a couple of years ago. Basically this process reads a file line by line, so the process of parsing data can begin immediately. It also handles memory much more efficiently.
Using Jeffrey’s code as an example, I updated the application and now the process takes less than 3 minutes.
However, the entire process had usually been
- Upload file
- Import file
- Delete file
I ran into a problem trying to delete the file after the import was complete. Why? Because the FileReader still had ownership of the file.
Here’s a snippet of the code from Jeffry’s article:
<cfscript>
fileReader = CreateObject("java", "java.io.FileReader");
fileReader.init("C:\\test.txt");
br = CreateObject("java", "java.io.BufferedReader");
br.init(fileReader);
<!--- ... --->
</cfscript>
fileReader.init() is where the file is “opened” before it is passed to the BufferedReader. Now we just need to close the file.
<cfset fileReader.close() />
Now the file can be deleted.
The Coldfusion 8 solution
This functionality has been made seamless thanks to an update to CFLOOP that masks the use of java.io.BufferedReader.
<cfloop file="C:\\test.txt" index="x" />
Adrian J. Moreno
Adrian is a CTO and solution architect specializing in software modernization. More information