Using Java BufferedWriter to create CSV files
Someone recently asked me to expand upon my previous post about generating CSV files, and in particular, to focus on the Java method. In my previous post, I concluded that using the Java BufferedWriter class is a much more scalable and stable solution than using the typical concatenate-and-write-once-done method.
Step by Step
There really isn't much to using Java to write to a file. Essentially, there are three steps, 1) create the Java class instances, 2) get the data and write to the buffer, and 3) close the output stream.
Firstly, we instantiate the FileWriter class (which writes to the file) and then the BufferedWriter class, passing the FileWriter instance as a parameter.
-
<cfscript>
-
outputFile = getDirectoryFromPath(GetCurrentTemplatePath()) & "dump.csv";
-
oFileWriter = CreateObject("java","java.io.FileWriter").init(outputFile,JavaCast("boolean","true"));
-
oBufferedWriter = CreateObject("java","java.io.BufferedWriter").init(oFileWriter);
-
</cfscript>
Then, we create the column headers, and loop over the data (query in this case) and write it to the buffer. The Java class manages the size of the buffer internally, so when threshold is reached, it will write to the file.
-
<cfset oBufferedWriter.write("LASTNAME,FIRSTNAME" & chr(13) & chr(10))>
-
<cfloop query="qData">
-
<cfset oBufferedWriter.write(chr(34) & lastname & chr(34) & ",")>
-
<cfset oBufferedWriter.write(chr(34) & firstname & chr(34) & chr(13) & chr(10))>
-
</cfloop>
Lastly, we need to close the output stream, otherwise the file will not be released.
-
<cfset oBufferedWriter.close()>
Full code
-
<cfscript>
-
outputFile = getDirectoryFromPath(GetCurrentTemplatePath()) & "dump.csv";
-
oFileWriter = CreateObject("java","java.io.FileWriter").init(outputFile,JavaCast("boolean","true"));
-
oBufferedWriter = CreateObject("java","java.io.BufferedWriter").init(oFileWriter);
-
</cfscript>
-
-
<cfquery datasource="cfartgallery" name="qData">
-
SELECT *
-
FROM artists
-
ORDER BY lastname, firstname
-
</cfquery>
-
-
<cftimer type="inline" label="Generate CSV">
-
<cfset oBufferedWriter.write("LASTNAME,FIRSTNAME" & chr(13) & chr(10))>
-
-
<cfloop query="qData">
-
-
<cfset oBufferedWriter.write(chr(34) & lastname & chr(34) & ",")>
-
<cfset oBufferedWriter.write(chr(34) & firstname & chr(34) & chr(13) & chr(10))>
-
-
</cfloop>
-
<cfset oBufferedWriter.close()>
-
</cftimer>
