Java - Do not overwrite with bufferedwriter

user1051477 picture user1051477 · Dec 21, 2011 · Viewed 8.9k times · Source

I have a program that add persons to an arraylist. What I'm trying to do is add these persons to a text file as well but the program overwrites the first line so the persons get erased.

How do I tell the compiler to write at the next free line?

import java.io.*;
import java.util.*;
import javax.swing.JTextArea;

public class Logic {

File file;
FileWriter fw;
FileReader fr;
BufferedWriter bw;
ArrayList<Person> person;

public Logic() {
    try {
        file = new File("register.txt");

        if (!file.exists()) {
            file.createNewFile();
        }
    } catch (IOException e) {
    }

    person = new ArrayList<Person>();
}

// Add person
public void addPerson(String name, int tele) {
    person.add(new Person(name, tele));
    savePerson(name, tele);
}

// Save person to external file
public void savePerson(String name, int tele) {
    try {
        fw = new FileWriter(file.getName());
        bw = new BufferedWriter(fw);
        String tel = Integer.toString(tele);
        bw.write(name + "\t" + tel);
        bw.newLine();
        bw.close();

    } catch (Exception e) {
        System.out.println("skrev inte ut med buffered");
    }
}

// Går in i alla objekt av klassen Person och skriver ut toString i
// textArean
public void visaAlla(JTextArea textRuta) {
    textRuta.setText("");
    // for(Person p:person)
    // {
    // textRuta.append(p.toString());
    // }

    try {
        fr = new FileReader(file.getName());
        BufferedReader in = new BufferedReader(fr);
        String str;

        while ((str = in.readLine()) != null) {
            textRuta.append(str);
        }

    } catch (Exception e) {
        System.out.println("gickcinte ");
    }
}
}

Answer

Sanjay T. Sharma picture Sanjay T. Sharma · Dec 21, 2011

FileWriter takes an optional boolean argument which specifies whether it should append to or overwrite the existing content. Pass in true if you want to open the file for writing in append mode.