> I have a log file that I'm looking to parse. I only care about the
> last entry. Is it possible to read in the file, then loop over it from
> the end, rather than the beginning? Here's the code I've got right now.
> It works well, but why loop over parts that aren't needed right?
I do not think there are any CF functions that do this. It is possible with
java. Though not quite as elegant as what you have now. Whether it would
ultimately be more efficient, I do not know.
Here is a down-and-dirty example. Bear in mind I have completely ignored
encoding for the moment. That is not my area of expertise ;)
<cfscript>
// set the number of lines to retrieve
numOfLines = 2;
logFilePath = server.coldFusion.rootDir & "/logs/exception.log";
// open the file for random access
accessFile = createObject("java", "java.io.RandomAccessFile").init(
logFilePath, "r" );
size = accessFile.length();
// set the number of bytes to grab in each loop
chunkSize = 1024;
Byte = createObject("java", "java.lang.Byte");
byteArray = createObject("java","java.lang.reflect.Array").newInstance(
Byte.TYPE, javacast("int", chunkSize) );
// move to the end of the file
accessFile.seek( size );
// determine the maximum number of bytes that can be read
grabBytes = min( chunkSize, accessFile.getFilePointer() );
lineCount = 0;
lineArray = [];
newLine = chr(10);
String = createObject("java", "java.lang.String");
keepSearching = true;
while (grabBytes > 0 AND keepSearching) {
// move to the correct starting position
startAt = accessFile.getFilePointer() - grabBytes;
accessFile.seek( startAt );
// read the next set of bytes and convert to string
accessFile.readFully( byteArray, javacast("int", 0), javacast("int",
grabBytes) );
line = String.init( byteArray );
foundAt = find(newLine, line);
// if one or more newlines were found ..
if ( foundAt ) {
// split the string into lines and save to a CF array
results = line.split( "\n" );
for ( x = arrayLen(results); x > 0; x--) {
arrayPrepend( lineArray, results[x]);
lineCount++;
// exit when desired number of rows was found
if ( lineCount >= numOfLines ) {
keepSearching = false;
break;
}
}
}
accessFile.seek( startAt );
grabBytes = min( chunkSize, accessFile.getFilePointer() );
}
accessFile.close();
</cfscript>
<cfdump var="#lineArray#">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
Adobe® ColdFusion® 8 software 8 is the most important and dramatic release to
date
Get the Free Trial
http://ad.doubleclick.net/clk;192386516;25150098;k
Archive:
http://www.houseoffusion.com/groups/CF-Talk/message.cfm/messageid:304966
Subscription: http://www.houseoffusion.com/groups/CF-Talk/subscribe.cfm
Unsubscribe: http://www.houseoffusion.com/cf_lists/unsubscribe.cfm?user=89.70.4