简体   繁体   中英

Problems with reading from a file in java, .txt file always erases

I'm taking a Grade 11 course in Java right now, and thus I am new to programming in Java. My assignment is to ask the user their name and a password, put their password on a .txt (the .txt file's name would be the name they input), and ask if they've played before (that's for the second half of the assignment). If they enter 'no' it will ask them to input a password for the future. If they exit and run the program again and input 'yes' then it will prompt the user to input the password they put in when they said 'no'.

Here's the code:

import java.io.*;
class passwordtest
{
public static void main (String args[])
    throws java.io.IOException
{
    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));

    String name, password, input, filepassword;

    System.out.println ("Please enter your name");
    name = br.readLine ();
    FileWriter fw = new FileWriter (name + ".txt");

    System.out.println ("Have you played this game before?");
    input = br.readLine ();

    if (input.equalsIgnoreCase ("no"))
    {
        System.out.println ("Please enter a password that you can use for later.");
        password = br.readLine ();
        fw.write (password);
        fw.close ();
    }

    if (input.equalsIgnoreCase ("yes"))
    {
        FileReader fr = new FileReader (name + ".txt");
        BufferedReader bfr = new BufferedReader (fr);
        filepassword = bfr.readLine ();

        System.out.println ("Please enter your password");
        password = br.readLine ();

        if (!password.equals (filepassword))
        {
            System.out.println ("Wrong password.");
        }
        if (password.equals (filepassword))
        {
            System.out.println ("Right password. Enjoy the program!");
        }
    }
}

}

The problem here is that every time I run the program to say 'yes' the .txt file erases, thus making it impossible for me to be able to see if the user entered the correct password. I've been struggling with this for the past couple of hours, please help.

FileWriter fw = new FileWriter (name + ".txt");

This is enough to create a new file. Place it carefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM