Java-不要用bufferedwriter覆盖 [英] Java - Do not overwrite with bufferedwriter

查看:455
本文介绍了Java-不要用bufferedwriter覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将人员添加到arraylist的程序.我正在尝试将这些人员也添加到文本文件中,但是程序会覆盖第一行,因此这些人员将被删除.

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 ");
    }
}
}

推荐答案

FileWriter使用

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.

这篇关于Java-不要用bufferedwriter覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆