StringBuffer To File Java Example /*         StringBuffer To File Java Example         This example shows how to write c...

StringBuffer To File Java Example

02:39 PASSOVE INCOME 0 Comments

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

0 comments: