Read File line by line in ColdFusion by using Java Classes

HI,
I was having situation where I wanted to read a file and process each line.
I think cffile tag is not capable to do it, so I use java classes.
Basically we need two kinds of classes.
1. InputSream
2. Buffer reader

Buffer reader is capable to read any input stream line by line.

Final code will look like:

<cfscript>
	FileName = expandPath('/temp.txt');
	objFileReader = createObject("java","java.io.FileReader");
	InputStreamReader = objFileReader.init(FileName);
	objBuffer = createObject("java","java.io.BufferedReader" );
	LineIO = objBuffer.init(InputStreamReader);
	</cfscript>
	
	<cfset eof = 0>
	<cfset cnt = 1>
	<cfloop condition="not eof">
	<cfset currline = LineIO.readline()>
	<cfif isdefined("currline") eq "no">
	<cfset eof = 1>
	<cfbreak>
	</cfif>
	<cfoutput>line #cnt#: #currline#<br/></cfoutput>
	<cfset cnt = cnt + 1>
	<cfflush>
	</cfloop>

Comments

Brooklyn

I like the Java way, but as usual what's easier than Coldfusion.

<cfloop file="c:\temp\myfile.txt" index="theline">

<cfoutput>#theline#</cfoutput>

</cfloop>

November 6, 2011, 6:05 PM
Reply
Vikas

Thanks Brooklyn! I didn't know that!

November 10, 2011, 12:12 AM
Reply
NOTE : Comments are moderated, and will not appear until the author has approved them.
Post a Comment
  1. Leave this field empty

Required Field