Blog Archive

Java write to file using BufferedWriter example

BufferedWriter provides efficient method of writing single characters, arrays, and strings. You can specify a buffer size but the default is large enough for most purposes. A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.

package com.as400samplecode;

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

public class FileBufferedWriter {

 public static void main(String[] args) {
 
  BufferedWriter bufferedWriter = null;
  
  try {

   File file = new File("data/newFile.txt");
   //to append more data to the existing file change the line to
   //File file = new File("data/newFile.txt",true);
   
         //if file doesn't exists, then create it
         if(!file.exists()){
      file.createNewFile();
         }
 
         FileWriter fileWriter = new FileWriter(file);
         bufferedWriter = new BufferedWriter(fileWriter);
         bufferedWriter.write("My first line!");
         bufferedWriter.newLine();
         bufferedWriter.write("My second line ");
         bufferedWriter.write("keeps going on...");
         bufferedWriter.newLine();
      
    
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (bufferedWriter != null){
     bufferedWriter.close();
    }
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }
  
 }

}


No comments :

Post a Comment