我正在尝试使一个循环获取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.");
}
}
}
谢谢。
最佳答案
根据Javadoc
状态(粗体为我自己):
用作此格式化程序目标的文件。如果文件
存在,它将被截断为零大小;否则,一个新文件
将被创建。输出将被写入文件,并且是
缓冲的。
您可以使用类似这样的方法来避免文本被截断:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("programOutput.txt", true)));