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();
   }
  }
  
 }

}


5 comments :

  1. i want to read an array from a file and sort it and store it in an another file using buffered array help me..

    ReplyDelete
  2. We are offering Website service, E-commerce website and much more......

    Phone System

    ReplyDelete
  3. Perfect. Exactly what i was looking for. Writing is a artistic talent. Writing can open the doors to wonderful teaching, mentoring, research and even administrative opportunities. I have a site for students personal statement writing services to improve their writing skills

    ReplyDelete