Write files in Java using BufferedWriter class

April 28, 2008 at 7:26 am Leave a comment

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.

Advertisements

Entry filed under: Script. Tags: , , .

MySQL JDBC Driver. Connect to MySQL from Java Visual Studio 2008 and .NET Framework 3.5 Service Pack 1 Beta

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


April 2008
M T W T F S S
    Jun »
 123456
78910111213
14151617181920
21222324252627
282930  

%d bloggers like this: