1

I am try to write a java code that will create a .txt file to any directory. And, the code will write some strings to the file & save the text to that file. I have wrote a code that can write to a file, but it can't save the text to my file. Each time I run my code and the new text override the existing text.

Here is my code:

package com.mahbub.file_object;

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

public class WriteFile {

    private static String content = "I am a text message!!";
    private static BufferedWriter bw;

    public static void main(String[] args) {
        File file = new File("D:/test.txt");

            try {
                FileWriter fw = new FileWriter(file);
                bw = new BufferedWriter(fw);                
                bw.write("I am 2nd line");
                bw.newLine();
                bw.write(content);

                bw.close();
                System.out.println("done!!");

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

    }
}

I want every text line will add into the file one after another without overriding. Can anyone help me? Thanks in advanced!!

mahbub_siddique
  • 1,755
  • 18
  • 22
  • 2
    [Check APIs](http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)): There is another constructor for `FileWriter` that supports the `append` option. – BackSlash Sep 01 '14 at 08:21

2 Answers2

5

Use this constructor:

FileWriter(File file, boolean append) 

"Constructs a FileWriter object given a File object."

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

4

Open your file in append mode, So that it won't override.

FileWriter writer= new FileWriter(fileObj.getAbsoluteFile() ,true); //flag to append
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307