Recommand · May 14, 2022 0


How can I compare User and password input to a text file?

Heyoo! I’m creating a simple login form using the swing package in java and I am having trouble in checking if the username and password is correct or not.

this here is the code currently:

public void actionPerformed(ActionEvent e) {
    try{
    File user = new File("Usernames.txt");
    File pass = new File("Passwords.txt");
    FileReader frUsername = new FileReader(user);
    FileReader frPassword = new FileReader(pass);
    BufferedReader brUsername = new BufferedReader(frUsername);
    BufferedReader brPassword = new BufferedReader(frPassword);
    String username = brUsername.readLine();
    String password = brPassword.readLine();

    if (e.getSource() == btnLogin){
        while(username != null && password != null){
           
        if ((txtUsername.getText()).equals(username) && (new String (jpfPassword.getPassword()).equals(password))){
            JOptionPane.showMessageDialog(null, "Welcome: " + username, "Login Successful",JOptionPane.INFORMATION_MESSAGE); //this is for testing purposes only
        }
        else{
            JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Unable to Login",0); //this is for testing purposes only
        }
       
        break;
    }
    }
    brUsername.close();
    brPassword.close();
}
    catch(IOException err){
        System.err.println("File not found.");
    }
}

}

The idea is to have multiple accounts stored in the password and usernames files. for example the file content is:

Username.txt:

       SampleUsername1
       SampleUsername2

Password.txt:

    SamplePassword1
    SamplePassword2

If line 1 from the username file is "sampleUsername1" then the password for it is also from line 1 "samplePassword1" of the password file. if the user and password isn’t the same line or not in the file, it should give an "invalid" error. I know it is not secure to put passwords in a txt file but this is only for practice purposes as I am still learning how to code. Any kind of help and tips is really appreciated. Thanks!




You may also like…




amazon-web-services android angular api arrays c# css dart dataframe django docker excel express firebase flutter html ios java javascript jquery json kotlin laravel linux list mongodb mysql node.js pandas php postgresql python python-3.x r react-native reactjs regex spring spring-boot sql sql-server string swift typescript vue.js