BufferedWriter Write String into File in Java - Java @ Desk

Monday, March 31, 2014

BufferedWriter Write String into File in Java

BufferedWriter Write String into File in Java

java.io.BufferedWriter class is used to write string into a file in java.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.FileWriter object and creates the new file if the file does not exists.

Its very important to call the flush() and close() method on the BufferedWriter otherwise contents will not be written to the file created.

This implementation will over write the content in the file. If you want to append the content to end of existing file click BufferedWriter Append String to End of Existing File in Java

To write using BufferedWriter following methods can be used :
1) write(String s) - It simply writes the String passed to this method
2) write(String s, int off, int len) - It writes the String from index off till len. If offset > 0 then len must be equal to len - off, otherwise it will throw java.lang.StringIndexOutOfBoundsException: String index out of range:

package test;

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

public class BufferedWriterWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  BufferedWriter bufferedWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file); // This will create new file if
            // it does not exists
   bufferedWriter = new BufferedWriter(fileWriter);
   String content = "Write this to file";
   bufferedWriter.write(content, 0, content.length());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   bufferedWriter.flush();
   bufferedWriter.close();
   fileWriter.close();
  }
 }
}






No comments:

Post a Comment