【问题标题】:Why doesnt this code store multiple inputs - currently stores only one that gets overwritten upon new input为什么此代码不存储多个输入 - 当前仅存储一个在新输入时被覆盖的输入
【发布时间】:2020-04-23 18:40:49
【问题描述】:

大家好,我们将不胜感激。

我创建了一些代码,允许我从终端获取用户输入,并将其保存到同一目录中的 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);
            }
}

}

感谢您的帮助!

【问题讨论】:

  • 您需要以追加模式打开编写器。如果没有,您将覆盖输入文件。取消注释您那里的/*, true*/

标签: java xml client-server writetofile


【解决方案1】:

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

【讨论】:

  • 我不敢相信就是这样,一直盯着那个特定的代码一个小时,每次都必须完全看过去。谢谢!
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多