Java - do not overwrite with buffer

I have a program that adds people to arraylist. What I'm trying to do is add these persons to a text file, but the program overwrites the first line so that people are erased.

How to tell the compiler to write 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 "); } } } 
+8
java overwrite line bufferedwriter
source share
1 answer

FileWriter takes an optional boolean argument that indicates whether to add or overwrite existing content. Go to true if you want to open the file for recording in add mode.

+12
source share

All Articles