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 ");
}
}
}
- BufferedWriter. close() flushes the buffer to the underlying stream, so if you forget to flush() and don't close, your file may not have all the text you wrote to it.
FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better.
When you create a Java FileWriter you can decide if you want to overwrite any existing file with the same name, or if you want to append to any existing file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With