使用缓冲类型writer java附加文本文件

时间:2014-05-15 09:27:19

标签: java

我试图存储用户输入的数据并将其存储在文本文件中以便以后操作,我有问题继续覆盖数据代码的第一行下面:

public void AddDataToFile(int i)

{
    BufferedWriter writer = null;
    try {

        writer = new BufferedWriter(new FileWriter("./Cat Info.txt"));

        Cat catCurrent;
        catCurrent = catPenArray [i];            
        writer.append("Pen Number " + (i + 1));
        writer.newLine();
        writer.write("Cat Name " + catCurrent.CatName);
        writer.newLine();
        writer.write("Cat Gender " + catCurrent.Gender);
        writer.newLine();
        writer.write("Chip Number " + catCurrent.ChipNumber);
        writer.newLine();
        writer.write("Arival Date " + catCurrent.ArrivalDate);
        writer.newLine();
        writer.write("Departure Date " + catCurrent.DepartureDate);
        writer.newLine();
        writer.write("How often fed " + catCurrent.HowOftenFed);
        writer.newLine();
        writer.write("Type Of food " + catCurrent.Food);
        writer.newLine();
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                System.err.println(e);
            }
        }
    }
} 

1 个答案:

答案 0 :(得分:2)

BufferedWriter不是问题 - 这就是你构建FileWriter的方式。您只需使用constructor overload which takes an append parameter

即可
new FileWriter("./Cat Info.txt", true)

我个人会尽量避免使用FileWriter:它不允许您指定编码,这意味着它将始终使用平台默认编码。我更喜欢使用FileOutputStream,并将其包装在OutputStreamWriter中,明确指定编码(通常为UTF-8)。同样,FileOutputStream有一个构造函数,允许您追加而不是覆盖。