javaxmlclient-serverwritetofile

Why doesnt this code store multiple inputs - currently stores only one that gets overwritten upon new input


Hey guys any help would be appreciated.

I've created some code that allows me to take user input from terminal, and saves it into a txt file in the same directory. The issue is that only 1 name and surname is stored each time. when i open a new client and type a different name, it will just overwrite the original one. not sure what is the cause as i was under the impression that the out.newline would solve this issue.

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);
            }
}

}

thanks for the help!


Solution

  • This is happening simply because you didn't open your FileWriter in the append mode, so it doesn't overwrite the file every time. To do this, you have to call the constructor as new FileWriter("TESTING.txt", true). Just uncomment the true and it'll work. I'm guessing at some point you accidentally commented that out.