0

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
CSE
  • 73
  • 6
  • At which line you are getting ? – techasutos Dec 20 '22 at 09:37
  • I think you are not reading `username` and `password`, but you are reading `name` and `roll` lines. And therefor substring(10) is not working in my opinion. – Zavael Dec 20 '22 at 09:47
  • @DevilsHnd answer helps me a lot. I think so that I can't read `username` or `password` and i've changed the values under `substring` also but it never gave me any results. – CSE Dec 20 '22 at 11:12

2 Answers2

1

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.

Update - Using a different file Reader:

This is the same code but utilizing a different reader. Here we use a BufferedReader in combination with a FileReader. Again, Try With Resources is used here to auto-close the reader and free resources when reading has completed. Make sure your Student.txt file is located within the project folder or provide a complete path to the Student.txt data file (ex: "C:/MyStudentFiles/Student.txt" or "C:\\MyStudentFiles\\Student.txt":

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 when done.               */ 
    try (BufferedReader reader = new BufferedReader(new FileReader("Student.txt"))) {
        String line;
        // Read in each line one by one...
        while ((line = reader.readLine()) != null) {
            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.readLine();
                /* 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;
                }
            }
        }
    }
    catch (IOException ex) {
        // Trap FileNotFoundException and inform User:
        JOptionPane.showMessageDialog(this, ex.getMessage(),
                "Student File Read Error!", JOptionPane.WARNING_MESSAGE);
    }

    // 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!
    }
}

If you are actually using the code above then all should work.

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
  • This work . But it's an error shows like `try (Scanner reader = new Scanner (new File("Student.txt")))` in this line and said to compile the project in jre1.7 While I am useing java19 – CSE Dec 20 '22 at 11:09
  • I'm Sorry. I don't use Java 19. I use a high flavor of Java 8. What part of that line does your IDE not like? – DevilsHnd - 退職した Dec 24 '22 at 19:44
  • 1
    @CSE - I have added additional code at the end of my post which utilizes a different reader. This should work. A BufferedReader/FileReader is used. – DevilsHnd - 退職した Dec 25 '22 at 01:05
-3

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

devMe
  • 126
  • 10
  • It doesn't help :( – CSE Dec 20 '22 at 09:25
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 21 '22 at 12:46