我正在尝试循环获取用户输入的信息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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
根据Javadoc州(我自己的粗体文字):
用作此格式化程序目标的文件.如果该文件存在,那么它将被截断为零大小 ; 否则,将创建一个新文件.输出将写入文件并进行缓冲.
您可以使用类似的东西来避免文本被截断:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("programOutput.txt", true)));
Run Code Online (Sandbox Code Playgroud)