How can I read a simple text file, processing each line of the file?
ColdFusion makes it easy to read a file using the <cfloop> tag. By using the file attribute, you can tell <cfloop> to iterate over each line of a file. This sample reads in a text file and displays each line:
<cfloop index="line" file="#myfile#">
<cfoutput>
The current line is #line# <br />
</cfoutput>
</cfloop>
This question was written by Hal Helms.
It was last updated on July 1, 2008 at 9:38:29 AM EDT.
CFML Referenced
Categories
Comments
Comment made by D K on February 22, 2006 at 12:09 PM
there is another way of doing this using the underlying java access you will have with Coldfusion. I've found this way to be more reliable than trying to use the carriage return type list delimiting
This article explains it nices (written by Jeffry Houser) http://coldfusion.sys-con.com/read/86121.htm
Comment made by Paul Carney on March 1, 2006 at 11:34 AM
Agreed - for large files, especially, the Java classes handle this much better. <cffile> did not operate efficiently and even crashed at times.
We we switched to using the Java classes, it was not only faster but more reliable. And Jeffry's article showed how to easily do this with Java.
Comment made by Gary Funk on August 31, 2006 at 9:45 PM
Jeffry's article is good but he forgot to CLOSE the file. That caused me a lot of greif when I tried to use <cffile action="rename" .... Opps.
Comment made by Ben Nadel on July 1, 2008 at 10:20 AM
I believe that the CF8 file loop iterator is actually using the Java line number reader, which implements a buffered reader internally. I could be making that up , but I thought that is what Forta says. If that is the case, I would assume it to be just as good as using the Java directly.
Comment made by Raymond Camden on July 1, 2008 at 10:27 AM
Yep, I can 100% confirm that. Of course, most of the time people like to read a portion of a file. You can use the file funcs for that. I just wish CF8 supported seek(). It lets you jump to a part of a file. It would be useful for stuff like MP3 ID3 info which begins at the end of the file.