Friday 26 April 2013

How to append data in a existing File using Java?

Code to append data in a existing file

Sample code:-

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

public class AppendDataInFile {
    public static void main(String[] args) {
        try {
            String dataForAppend = "This content is going to append in the existing file";

            File file = new File("C:\\ImportantData.json");
            FileWriter fileWritter = new FileWriter(file, true);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write("\n" + dataForAppend);
            bufferWritter.close();
            System.out
                    .println("Data successfully appended in the existing File");
        } catch (IOException ioe) {
            System.out
                    .println("IOException Occurred during data append in File.."
                            + ioe.getMessage());
        }
    }
}

Result:-


Note:- Prior to execution of the above program, in the existing file ImportantData.json is having the below content.

{"age":25,"name":"Gaurav","relations":["WIFE","FATHER","MOTHER","SISTER"]}

So, after the successful execution of the above program, the content passed through the program is added in the file which is shown in the Result.

No comments:

Post a Comment