How to append content to file?

  • new FileWriter(file,true) to append new content to the end of a file.

FileWriter(file,true) -> Keep the existing content and append the new content to the end of a file.

package com.nourit.javaIO;

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

public class AppendContentToFile {

  public static void main(String[] args) throws IOException {
    BufferedWriter bufferedWriter = null;
    FileWriter fileWriter = null;

    try {

      String data = " This is new content";
      File file = new File("D:/tmp/nourit.txt");

      //if file doesnt exists, then create it
      if (!file.exists()) {
        file.createNewFile();
      }
      // true = append file -> new FileWriter(file, append);
      fileWriter = new FileWriter(file.getAbsoluteFile(), true);
      bufferedWriter = new BufferedWriter(fileWriter);

      bufferedWriter.write(data);

      System.out.println("Content is Done");

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
        if (bufferedWriter != null){
          bufferedWriter.close();
        }
        if (fileWriter != null){
          fileWriter.close();
        }
      }
    }
}

Output:

Content is Done

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*