1

嘿家伙任何帮助将不胜感激。

我创建了一些代码,允许我从终端获取用户输入,并将其保存到同一目录中的 txt 文件中。问题是每次只存储 1 个姓名和姓氏。当我打开一个新客户端并输入不同的名称时,它只会覆盖原来的名称。不知道是什么原因,因为我的印象是 out.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);
            }
}

}

谢谢您的帮助!

4

1 回答 1

1

发生这种情况仅仅是因为您没有在附加模式下打开 FileWriter,因此它不会每次都覆盖文件。为此,您必须将构造函数调用为new FileWriter("TESTING.txt", true). 只需取消注释 true 即可。我猜你在某个时候不小心把它注释掉了。

于 2020-04-23T18:48:08.660 回答