1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
/* StringBuffer To File Java Example This example shows how to write contents of StringBuffer to file using BufferedWriter and FileWriter Java classes. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class JavaStringBufferToFileExample { public static void main(String[] args) throws IOException { //create StringBuffer object StringBuffer sbf = new StringBuffer(); //StringBuffer contents sbf.append("StringBuffer contents first line."); //new line sbf.append(System.getProperty("line.separator")); //second line sbf.append("StringBuffer contents second line."); /* * To write contents of StringBuffer to a file, use * BufferedWriter class. */ BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("d:/demo.txt"))); //write contents of StringBuffer to a file bwr.write(sbf.toString()); //flush the stream bwr.flush(); //close the stream bwr.close(); System.out.println("Content of StringBuffer written to File."); } } /* Output of above given Write StringBuffer to File example would be Content of StringBuffer written to File. Contents of file "demo.txt" would be StringBuffer contents first line. StringBuffer contents second line. */ |
This line : sbf.append(System.getProperty(“line.separator”)); is no good. It introduces null values into my program when taking String data from an arraylist and putting it into a StringBuffer. Instead i just append “\n” to each arraylist value and it stores itself properly. What is .getProperty(“line.separator) ? Why use it ?