Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Do not overwrite with bufferedwriter

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 ");
    }
}
}
like image 764
user1051477 Avatar asked Dec 21 '11 10:12

user1051477


People also ask

Do we need to close BufferedWriter in Java?

- 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.

Which is better FileWriter vs BufferedWriter?

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.

Does FileWriter overwrite existing file?

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.


1 Answers

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.

like image 169
Sanjay T. Sharma Avatar answered Sep 30 '22 08:09

Sanjay T. Sharma