CFLib.org – Common Function Library Project

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

Last updated December 3, 2001

Version: 1 | Requires: ColdFusion 5 | Library: FileSysLib

 
Rated 0 time(s). Average Rating: 0

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:

view plain print about
<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:

view plain print about
<cfscript>
/**
 * 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;
}
</cfscript>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Tayo Akinmade Tayo Akinmade added
arrayTrim
10 day(s) ago

Will Belden Will Belden added
longTime
15 day(s) ago

James Sleeman James Sleeman added
quickSort
25 day(s) ago

Ben Forta Ben Forta added
GetHostAddress
28 day(s) ago

Top Rated

Darwan Leonardo Sitepu EksporSQLData
Rated 5.0, 16 time(s)

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 13 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson