Thursday, March 4, 2010

JAVA - Writing a StringBuffer to a File

During some recent development work I was using a StringBuffer to hold a large string (>400K characters). This string was built using a variety of methods based upon data being read in from a CSV file.

Once the StringBuffer had been created I was going to write the StringBuffer out to a file. This is where I had an issue. For some reason I thought that stringBuffer included a method to write the information to a file. It doesn't.

I then went looking for an easy way to write the contents of the StringBuffer to a text file. After looking at a few forum posts I managed to determine the simplest way to write the StringBuffer to the file.

StringBuffer output = new StringBuffer();
// Get the correct Line Separator for the OS (CRLF or LF)
String nl = System.getProperty("line.separator");
String filename = "output.txt";
output.append("Write First Line to StringBuffer");
output.append("Write Second Line to StringBuffer");

try {
  BufferedWriter out = new BufferedWriter(
                       new FileWriter(filename));
  String outText = output.toString();
catch (IOException e)

The interesting parts of this code is the use of System.getProperties to get the correct line separator for the OS the code is running on and the use of the BufferedWriter in conjunction with a FileWriter to write the StringBuffer to the file.