Skip to Content

StringBuffer To File Java Example

  1. /*
  2.         StringBuffer To File Java Example
  3.         This example shows how to write contents of StringBuffer to file using BufferedWriter
  4.         and FileWriter Java classes.
  5. */
  6.  
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileWriter;
  10. import java.io.IOException;
  11.  
  12. public class JavaStringBufferToFileExample {
  13.        
  14.         public static void main(String[] args) throws IOException {
  15.                
  16.                 //create StringBuffer object
  17.                 StringBuffer sbf = new StringBuffer();
  18.                
  19.                 //StringBuffer contents
  20.                 sbf.append("StringBuffer contents first line.");
  21.                 //new line
  22.                 sbf.append(System.getProperty("line.separator"));
  23.                 //second line
  24.                 sbf.append("StringBuffer contents second line.");
  25.                
  26.                 /*
  27.                  * To write contents of StringBuffer to a file, use
  28.                  * BufferedWriter class.
  29.                  */
  30.                
  31.                 BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("d:/demo.txt")));
  32.                
  33.                 //write contents of StringBuffer to a file
  34.                 bwr.write(sbf.toString());
  35.                
  36.                 //flush the stream
  37.                 bwr.flush();
  38.                
  39.                 //close the stream
  40.                 bwr.close();
  41.                
  42.                 System.out.println("Content of StringBuffer written to File.");
  43.         }
  44. }
  45.  
  46. /*
  47. Output of above given Write StringBuffer to File example would be
  48. Content of StringBuffer written to File.
  49.  
  50. Contents of file "demo.txt" would be
  51. StringBuffer contents first line.
  52. StringBuffer contents second line.
  53. */