Java Examples - Append String to a File


Advertisements


Problem Description

How to append a string in an existing file ?

Solution

This example shows how to append a string in an existing file using filewriter method.

import java.io.*;

public class Main {
   public static void main(String[] args) throws Exception {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
         out.write("aString1\n");
         out.close();
         out = new BufferedWriter(new FileWriter("filename",true));
         out.write("aString2");
         out.close();
         BufferedReader in = new BufferedReader(new FileReader("filename"));
         String str;
         
         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
      }
      in.close();
      catch (IOException e) {
         System.out.println("exception occoured"+ e);
      }
   }
}

Result

The above code sample will produce the following result.

aString1
aString2

The following is an example of append a string in an existing file in java

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

public class AppendToFileExample {
   public static void main( String[] args ) { 
      try { 
         String data = " Tutorials Point is a best website in the world";
         File f1 = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
         if(!f1.exists()) {
            f1.createNewFile();
         } 
         FileWriter fileWritter = new FileWriter(f1.getName(),true);
         BufferedWriter bw = new BufferedWriter(fileWritter);
         bw.write(data);
         bw.close();
         System.out.println("Done");
      } catch(IOException e){
         e.printStackTrace();
      }
   }
}

The above code sample will produce the following result.

Done

java_files.htm

Advertisements