Reading a text file, one line at a time
The problem with parsing text files is that the common method is to load the entire file into memory and then loop over it as a list element. With CFML, that is the only way to do it. However, if the file is large, it can cause problems. CF5 and below, for example, will blow chunks and commit suicide if you try to load a 5 meg file into memory. With MX, you can load a large file into memory and it'll chew through it like a hot knife through butter but it can take quite some time to load a file into memory and then you have a much larger memory footprint to concern yourself with.
And what if you needed to parse a 200 meg text file? S.O.L.?
With CF5, you were. However, with MX's ability to create java objects, you can interface with the Java subsystem and access the text files with it. Using this method, you can read in a file one line at a time with little to no delays.
If you want to parse in a text file one line at a time instead of reading the entire file into memory, this little block of code will handle that for you. Put in your text file, path and file name, in the FileName filed and run the template. It seems to work fine with both Unix and Windows line breaks.
Example HTML/CFML code: Code:
<cfscript>
// Define the file to read, use forward slashes only
FileName="C:/Example/ReadMe.txt";
// Initilize Java File IO
FileIOClass=createObject("java","java.io.FileReader");
FileIO=FileIOClass.init(FileName);
LineIOClass=createObject("java","java.io.BufferedReader" );
LineIO=LineIOClass.init(FileIO);
</cfscript>
<CFSET EOF=0>
<CFLOOP condition="NOT EOF">
<!--- Read in next line --->
<CFSET CurrLine=LineIO.readLine()>
<!--- If CurrLine is not defined, we have reached the end of file --->
<CFIF IsDefined("CurrLine") EQ "NO">
<CFSET EOF=1>
<CFBREAK>
</CFIF>
<CFOUTPUT>#CurrLine#<br></CFOUTPUT><CFFLUSH>
</CFLOOP>