Implement a login validation system using file handling in JavaFX

  1. Create a text file called “users.txt” and store the login credentials in the following format:

username1 password1 ,username2 password2, username3 password3

Create a JavaFX class called “LoginValidation” and define the following method:

public static boolean validateLogin(String username, String password) {
   try {
       File file = new File("users.txt");
       Scanner scanner = new Scanner(file);
       while (scanner.hasNextLine()) {
           String line = scanner.nextLine();
           String[] tokens = line.split(" ");
           if (tokens[0].equals(username) && tokens[1].equals(password)) {
               return true;
   } catch (FileNotFoundException e) {
   return false;

In your JavaFX controller class, create a method that handles the login button’s click event and calls the “validateLogin” method. If the login is successful, show a message saying “Login successful!”, and if it fails, show a message saying “Invalid username or password.”

ow you could use the “validateLogin” method in a JavaFX controller class:

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

public class LoginController {
   private TextField usernameField;
   private PasswordField passwordField;

   private void handleLoginButtonAction() {
       String username = usernameField.getText();
       String password = passwordField.getText();
       if (LoginValidation.validateLogin(username, password)) {
           Alert alert = new Alert(Alert.AlertType.INFORMATION);
           alert.setTitle("Login Successful");
           alert.setContentText("Login successful!");
       } else {
           Alert alert = new Alert(Alert.AlertType.ERROR);
           alert.setTitle("Invalid Login");
           alert.setContentText("Invalid username or password.");

Leave a Reply