文件输出保持覆盖?

时间:2015-10-26 09:45:05

标签: java file io

我尝试循环获取用户输入的信息3次并将其保存到文件中。为什么文件不断被覆盖?我最初是在我的saveInfo()函数中实例化File类,但是我认为在构造函数中移动和处理它会有所帮助,但它没有?

注意:此类是从主类实例化的,然后调用go()。

package informationcollection;

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.Integer;

public class Getter {

    private String name;
    private int age;
    private File fp;


    public Getter () {
        name = "";
        fp = new File("programOutput.txt");
        System.out.println("The Getter class has been instanstiated!");
    }

    public void go() {
        getInfo();
        System.out.println("The information has been saved to a file!");
    }

    public void getInfo() {
        Scanner keyboard = new Scanner(System.in);
        int i;

        for(i=0;i<3;i++) {
            System.out.println("What is your name?");
            System.out.printf(">>: ");
            name = keyboard.nextLine();

            System.out.println("How old are you?:");
            System.out.printf(">>: ");
            age = Integer.parseInt(keyboard.nextLine());
            System.out.printf("We will save that your name is %s, and you are %d years old!\n", name, age);
            saveInfo();
        }

    }

    public void saveInfo() {
        try {
            Formatter output = new Formatter(fp);
            output.format("%s is %d years old!\n", name, age);
            output.flush();
        }
        catch (FileNotFoundException ex) {
            System.out.println("File doesn't exist.");
        }



    }



}

感谢。

4 个答案:

答案 0 :(得分:6)

根据Javadoc州(我自己的粗体文字):

  

用作此格式化程序目标的文件。 如果是文件   存在然后它将被截断为零大小;否则,一个新文件   将被创建。输出将被写入文件并且是   缓冲。

您可以使用类似的内容来避免文本被截断:

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("programOutput.txt", true)));

答案 1 :(得分:3)

您使用的Formatter构造函数的java api说明如下:

  

file - 要用作此格式化程序的目标的文件。如果该文件存在,那么它将被截断为零大小;否则,将创建一个新文件。

因此,每次调用Formatter(File file)构造函数时,都要删除文件中的所有内容。

要解决此问题,请将Formatter定义为类成员:

private String name;
private int age;
private File fp;
private Formatter output;

在构造函数中指定它:

public Getter () {
    try {
        name = "";
        fp = new File("programOutput.txt");
        output = new Formatter(fp);
        System.out.println("The Getter class has been instanstiated!");
    } catch (FileNotFoundException e) {
        System.out.println("File doesn't exist.");
    }
}

然后只需在saveInfo()方法中使用它!

答案 2 :(得分:2)

而不是Formatter默认构造函数,只需使用构造函数Formatter(Appendable a)

public Formatter(Appendable a)

这有助于你追加。

或转到FileWriter

FileWriter fw = new FileWriter(file.getAbsoluteFile() ,true);
  给定File对象的

Constructs a FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。

答案 3 :(得分:0)

检查java.util.Formatter的JavaDoc。它陈述如下:

  

如果该文件存在,那么它将被截断为零大小;否则,将创建一个新文件。

由于每次尝试保存信息时都会实例化新的Formatter,因此始终将文件截断为零大小。要防止这种情况发生,只需为您的类定义一个包含所述Formatter的新属性,并仅创建一次。