Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write File without deleting older data [duplicate]

Tags:

java

file-io

Possible Duplicate: java append to file How to append data to a file?

I want to write a file in java without cleaning(deleting) older data

This is my try, but the current data will be cleaned on writing new data.

import java.io.*;

public class WriteToFileExample {

public static void main(String[] args) {
    try {
        String content = "New content to write to file";

        File file = new File("/mypath/filename.txt");

        // if file doesnt exists, then create it
        if (!file.exists())
            file.createNewFile();

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
like image 469
Sajad Avatar asked Dec 18 '12 18:12

Sajad


2 Answers

Use constructor FileWriter(String filename, boolean append) that can instruct the file to be opened in append mode:

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
                                                     //^^^^ means append
like image 167
hmjd Avatar answered Nov 09 '22 11:11

hmjd


Try

FileWriter fw = new FileWriter(file, true);

Notes: second param means append; no need for file.getAbsoluteFile(), just File is OK

like image 3
Evgeniy Dorofeev Avatar answered Nov 09 '22 12:11

Evgeniy Dorofeev