java为什么这个代码不存储多个输入当前只存储一个在新输入时被覆盖的输入
嘿,伙计们,任何帮助都将不胜感激
我已经创建了一些代码,允许我从终端获取用户输入,并将其保存到同一目录中的txt文件中。问题是每次只存储一个姓名和姓氏。当我打开一个新的客户端并键入一个不同的名称时,它只会覆盖原来的名称。不知道是什么原因,因为我当时的印象是,这个问题已经解决了。newline将解决这个问题
public void userinput()
{
try
{
out = new BufferedWriter(new FileWriter("TESTING.txt"/*,true*/));
//
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//ask for first name
System.out.println("Please enter your first name: ");
Name = input.nextLine();
//ask for surname
System.out.println("Please enter your last name: ");
Surname = input.nextLine();
//write names into txt file
out.write(Name + " - " + Surname);
//print welcome message with names into console for user
System.out.println("Welcome " + Name + Surname);
out.newLine();
out.close();
}
catch(IOException e)
{
System.out.println("There was a problem:" + e);
}
}
}
谢谢你的帮助
# 1 楼答案
发生这种情况的原因很简单,因为您没有在追加模式下打开FileWriter,所以它不会每次都覆盖文件。为此,必须以
new FileWriter("TESTING.txt", true)
的形式调用构造函数。只要取消对true的注释,它就会工作。我猜在某个时候你不小心把它说出来了