Home > database >  Can't Login using .txt file in java
Can't Login using .txt file in java

Time:12-20

I want to login using .txt file using Username and Password. The file looks like below:

Name: Rahim
Roll: C20
Age: 24
Username: rahim
Password: 1234
_______________________________________________________________

Name: Karim
Roll: C24
Age: 25
Username: karim
Password: 45678
_______________________________________________________________

I use the below code for login:

btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String username,password;
                String user, pass;
                username = txtUser.getText();
                password = txtPass.getText();
                
                RandomAccessFile rf = new RandomAccessFile("Student.txt", "rw");
                long ln = rf.length();
                for(int i=0; i<ln; i =5) {
                    String line = rf.readLine();
                    user = line.substring(10);
                    pass = rf.readLine().substring(10);
                    
                    if(username.equals(user) && password.equals(pass)) {
                        JOptionPane.showMessageDialog(null, "Login Successfully");
                        break;
                    }
                    else if(i == (ln - 1)) {
                        JOptionPane.showMessageDialog(null, "Wrong!");
                    }
                    //For skipping checking the same things which are skipped already
                    for(int k=1; k<=5; k  ) {
                        rf.readLine();
                    }
                }
                
                rf.close();
            }
            catch(Exception ex) {
                //JOptionPane.showMessageDialog(null, "File Not Found!");
                ex.printStackTrace();
            }
        }
    });

But it can't help me to reach my goal and show error like this:

java.lang.StringIndexOutOfBoundsException: Range [10, 7) out of bounds for length 7

CodePudding user response:

Something like this should help. Read the comments in code:

public void actionPerformed(ActionEvent e) {
    String username = txtUser.getText();  // Get entered User Name
    String password = txtPass.getText();  // Get entered Password
    boolean loginSuccess = false;         // Flag to indicate success or failure.
        
    // Make sure the User actually supplied the required data:
    if (username.isEmpty() || password.isEmpty()) {
        JOptionPane.showMessageDialog(this, "<html>You <b>must</b> supply both "
                      "a User Name and a Password!", "Student File Not Found!", 
                    JOptionPane.WARNING_MESSAGE);
        return;
    }
        
    /* Open a reader. 'Try With Resources' is used here to 
       auto-close the reader and free resources.        */
    try (Scanner reader = new Scanner (new File("Student.txt"))) {
        String line;
        while (reader.hasNextLine()) {
            line = reader.nextLine();
            line = line.trim();
            /* If the line is blank or if the line does not start with 
               "Username:" then skip past it. If it does start with
               "Username:" then parse the line using the String#split()
               method to get the actual name. Is it the desired name? */
            if (!line.isEmpty() && line.startsWith("Username:") && 
                        line.split(":\\s*")[1].equalsIgnoreCase(username)) {
                // Yes it is...read in the next line which would be the password:
                String passwordLine = reader.nextLine();
                /* Parse the Password line to retrieve the password. Is it
                   the desired password?                    */
                if (passwordLine.split(":\\s*")[1].equals(password)) {
                    /* Yes it is... flag login as successful and exit 
                       reading loop.                        */
                    loginSuccess = true;
                    break;
                }   
            }
        }
        // Was login successfull?
        if (loginSuccess) {
            // Yes, it was...Inform User.
            JOptionPane.showMessageDialog(this, "Login Successful!");
        }
        else {
            // No, it wasn't...Inform User.
            JOptionPane.showMessageDialog(this, "<html>Login <font color=red><b>"
                                          "Failed!</b></font> Exiting...</html>");
            System.exit(0);     // Close Application!
        }
    }
    catch (FileNotFoundException ex) {
        // Trap FileNotFoundException and inform User:
        JOptionPane.showMessageDialog(this, ex.getMessage(), 
                "Student File Not Found!", JOptionPane.WARNING_MESSAGE);
    }
}

User name is not letter case sensitive but the Password is.

CodePudding user response:

Rather than using .txt file use .env file .Hope this will help here

  • Related