Write File without deleting older data [duplicate]

2019-01-12 11:18发布

问题:

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 at that file!

I run this code and see that all older data on .txt file was cleaned after every Run!

my code is here:

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

public class WriteToFileExample {

public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new File("/users/mkyong/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();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

回答1:

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


回答2:

Try

FileWriter fw = new FileWriter(file, true);

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



回答3:

open the file in append mode . like

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));


回答4:

FileWriter takes a boolean argument which specifies whether to overwrite or not.

Try this :

FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);

also visit :

http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29



标签: java file-io