CFLib.org – Common Function Library Project

FileRead(file[, from][, to][, NL])

Last updated December 03, 2001

author

Raymond Camden

Version: 1 | Requires: CF5 | Library: FileSysLib

Description:
This UDF will read a file using Java objects. You can also specify a range of line numbers to retrieve.

Return Values:
Returns a string.

Example:

<CFSET TheFile = ExpandPath("includes/cflib_style.css")>
<CFSET Contents = FileRead(TheFile,1,5)>
<CFOUTPUT>
<PRE>
#HTMLEditFormat(Contents)#
</PRE>
</CFOUTPUT>

Parameters:

Name Description Required
file The filename to read. Yes
from The line number specifying where to begin reading. No
to The line number specifying where to stop reading. No
NL Character to use for newlines. Defaults to Chr(13)Chr(10) No

Full UDF Source:

/**
 * Reads a file.
 * 
 * @param file      The filename to read. 
 * @param from      The line number specifying where to begin reading. 
 * @param to      The line number specifying where to stop reading. 
 * @param NL      Character to use for newlines. Defaults to Chr(13)Chr(10) 
 * @return Returns a string. 
 * @author Raymond Camden (ray@camdenfamily.com) 
 * @version 1, December 3, 2001 
 */
function FileRead(filename) {
    var fileStr = "";
    var fileReaderClass = createObject("java", "java.io.FileReader");
    var fileReader = fileReaderClass.init(filename);
    var lineNumberReaderClass = createObject("java","java.io.LineNumberReader");
    var lineReader = lineNumberReaderClass.init(fileReader);
    var notDone = true;
    var lastLine = 0;
    var thisLine = 0;
    var NL = Chr(13) & Chr(10);
    var from = 0;
    var to = 0;
    var line = "";
    
    //optional FROM
    if(arrayLen(arguments) gt 1) from = arguments[2];
    //optional TO
    if(arrayLen(arguments) gt 2) to = arguments[3];
    //optional NL
    if(arrayLen(arguments) gt 3) NL = arguments[4];
    
    if(not fileExists(filename)) return "";
    
    while(notDone) {
        line = lineReader.readLine();
        thisLine = lineReader.getLineNumber();
        if( (from is 0 OR thisLine gte from) AND (to is 0 OR thisLine lte to)) fileStr = fileStr & line & NL;
        if(thisLine is lastLine) notDone = false;
        lastLine = thisLine;
    }
    
    return fileStr;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson