CFLib.org – Common Function Library Project

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

Last updated December 3, 2001
Download UDF

author

Raymond Camden                                    Raymond Camden

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:

<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:

<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>

Search CFLib.org


Latest Additions

Shawn Porter Shawn Porter added
DeMoronize
3 hour(s) ago

Chris Carey Chris Carey added
readPropertiesFi...
1 day(s) ago

Randy Johnson Randy Johnson added
lastDayofWeek
3 day(s) ago

Frank Marion Frank Marion added
sitemapPing
7 day(s) ago

Top Rated

James Sleeman                                     QuickSort
Rated 5.0, 3 time(s)

Barney Boisvert indentXml
Rated 5.0, 3 time(s)

Nathan Dintenfass                                 queryColumnsToSt...
Rated 5.0, 3 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 3 time(s)

Created by Raymond Camden / Design by Justin Johnson