In Java, you can write data out to flat files using the BufferedWriter class. This class writes text out to a character output stream and buffers characters in order to provide an efficient means of writing single characters, arrays and strings.
This example also uses the FileWriter class inside of the BufferedWriter constructor. The FileWriter class is sort of a helper, or a convenient class enabling writing of character files.
I have a class that will return me a ResultSet from a Query against the NorthWind database Customers table. I define my BufferedWriter, loop through the ResultSet and write out the data to a flat delimited file.
try {
ResultSet rs = conn.GetResultSet(cn,”Select * from Customers”);
BufferedWriter writer = new BufferedWriter(new FileWriter(”c:/writerTest.txt”));
while(rs.next()){
String outLine=rs.getString(1)+”,”+rs.getString(2);
writer.write(outLine);
writer.newLine();
System.out.println(rs.getString(1) + ” ” + rs.getString(2));
}
rs.close();
cn.close();
System.out.println(”completed!”);
}
catch(Exception ex) {
//write out something here
}
If the File that you define in your FileWriter constructor does not exist, it will be created. Notice I use the writer.newLine(). This is so that the file prints with a carriage return/line-feed option and not continous accross one line.
Trackback this post | Subscribe to the comments via RSS Feed