I'm an RIA Developer who owns a motorcycle custom paint shop, who loves to race anything with wheels. I also enjoy woodworking, cooking, fine wines, liqueurs and dark beers. So if nothing else my blog should be eclectic.  
Aug 12 2008

Read text files one line at a time with ColdFusion

Posted by Russell Brown at 11:38 AM
5 comments
- Categories: ColdFusion | Java | Development

This is a pretty basic use of the how to capitalize on ColdFusion / Java, but I recently had to show someone else how to do this as well as use it myself today to parse a very large CSV file.

<cfscript>
    var f = "";
    var endOfFile = false;

    f = createObject("java","java.io.FileReader").init(arguments.csvFileLocation);
    f = createObject("java","java.io.BufferedReader").init(f);

    while (NOT endOfFile) {
        line = f.readLine();

        if (NOT isDefined("line")) {
            endOfFile = true;
            break;
        } else if (len(line)) {
            // {LINE PARSING CODE HERE}
        }
    }

    f.close();
</cfscript>

Comments

Scott Stroz

Scott Stroz wrote on 08/12/08 12:19 PM

In CF8 you can also use:

<cfloop file="{path to file}" index="line">
{code goes here}
</cfloop>
Adrian J. Moreno

Adrian J. Moreno wrote on 08/12/08 12:22 PM

If you're on ColdFusion 8, you can use the new CFLOOP syntax:

http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_j-l_15.html

<cfloop file="c:\temp\simplefile.txt" index="line">
      <cfoutput>#line#</cfoutput><br>
</cfloop>

All this does is abstract the call to java.io.BufferedReader. For CF 6 and 7, using java.io.BufferedReader is orders of magnitude faster than using CFFILE on large files.
Adrian J. Moreno

Adrian J. Moreno wrote on 08/12/08 12:24 PM

Ok, so the code is

[cfloop file="c:\temp\simplefile.txt" index="line"]
      [cfoutput]#line#[/cfoutput][br]
[/cfloop]
Peter Boughton

Peter Boughton wrote on 08/12/08 2:20 PM

Just in case anyone is unaware, CFHTTP can convert a CSV file to Query, which is much simpler than looping through a file and doing it yourself.

(Actually needing to parse a CSV file line by line is a fairly rare situation.)
Russell Brown

Russell Brown wrote on 08/13/08 8:39 AM

I'm not sure how I never knew about the cfloop file feature, but that's cool; now I feel like a tool newbie!!!

I'm parsing csv files to integrate with a legacy app/department that can't change how they do something with access (shutter). So I'm just writing an import for their data export...

Write your comment




(it will not be displayed)








Categories

Monthly Archives

Tech Blogs I Read

Motorcycle Links