Write to a File in Java using BufferedWriter

BufferedWriter

BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

BufferedWriter can be added around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.


BufferedWriter out
   = new BufferedWriter(new FileWriter("temp.txt"));

 

Java example to write to a File

 

package com.topjavatutorial.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class BufferedWriterDemo {

  public static void main(String[] args) {

    try {
      File file = new File("c://blogs//temp.txt");
      FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
      BufferedWriter out = new BufferedWriter(fileWriter);

      if (!file.exists()) {
        file.createNewFile();
      }

      String text = "This text will be added to File !!";

      out.write(text);

      out.close();
      fileWriter.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}


 

Output

temp.txt at c:/blogs folder contains following text :
 

write file in java

 

Note that, it will complain if the directory does not exist.

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags