简体   繁体   English

如何使用 BufferedReader 登录 function?

[英]How do make a login function using BufferedReader?

I am a first-year programming student and I was tasked to make a Login and Register program using Java Swing (Application Window) and BufferedReader+Writer.我是一年级编程学生,我的任务是使用 Java Swing(应用程序窗口)和 BufferedReader+Writer 制作一个登录和注册程序。 I am now able to write a username and password into a text file via BWriter, however I have no idea how to make the Login read the text file and only Login when the inputted username and password in their respected TextField matches the one I wrote into the text file.我现在可以通过 BWriter 将用户名和密码写入文本文件,但是我不知道如何让登录读取文本文件,并且只有在他们尊重的 TextField 中输入的用户名和密码与我写入的用户名和密码匹配时才登录文本文件。 (For reference the text file looks like this after I wrote the supposed username and password from the Register portion: Redman, 1234) (作为参考,在我从注册部分写入假定的用户名和密码后,文本文件看起来像这样:Redman,1234)

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.awt.event.ActionEvent;

public class Register {

    private JFrame frame;
    private JTextField tfNewUser;
    private JTextField tfNewPass;
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Register window = new Register();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Register() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setTitle("Register");
        frame.setBounds(100, 100, 286, 324);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        JLabel lblNewLabel = new JLabel("REGISTER ");
        lblNewLabel.setBounds(10, 11, 250, 26);
        lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 12));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        frame.getContentPane().add(lblNewLabel);
        
        tfNewUser = new JTextField();
        tfNewUser.setBounds(117, 48, 143, 20);
        frame.getContentPane().add(tfNewUser);
        tfNewUser.setColumns(10);
        
        tfNewPass = new JTextField();
        tfNewPass.setBounds(117, 79, 143, 20);
        tfNewPass.setColumns(10);
        frame.getContentPane().add(tfNewPass);
        
        JButton btnReg = new JButton("REGISTER");
        btnReg.setBounds(10, 110, 250, 23);
        btnReg.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            String regUser = tfNewUser.getText().toString();
            String regPass = tfNewPass.getText().toString();
            addReg(regUser, regPass);
            }
        });
        frame.getContentPane().add(btnReg);
        
        JButton btnUpdate = new JButton("UPDATE CREDENTIALS");
        btnUpdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                UpdateCreds newformu = new UpdateCreds();
                newformu.main(null);
                frame.setVisible(false);
            }
        });
        btnUpdate.setBounds(10, 213, 250, 23);
        frame.getContentPane().add(btnUpdate);
        
        JButton btnReturn = new JButton("RETURN TO LOGIN");
        btnReturn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Login newform = new Login();
                newform.main(null);
                frame.setVisible(false);
            }
        });
        btnReturn.setBounds(10, 142, 250, 23);
        frame.getContentPane().add(btnReturn);
        
        JLabel lblNewLabel_1 = new JLabel("New Username: ");
        lblNewLabel_1.setBounds(10, 48, 97, 14);
        frame.getContentPane().add(lblNewLabel_1);
        
        JLabel lblNewLabel_1_1 = new JLabel("New Password: ");
        lblNewLabel_1_1.setBounds(10, 82, 97, 14);
        frame.getContentPane().add(lblNewLabel_1_1);
        
        JButton btnDeleteAcc = new JButton("DELETE ACCOUNT");
        btnDeleteAcc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            deleteAcc();
            }
        });
        btnDeleteAcc.setBounds(10, 247, 250, 23);
        frame.getContentPane().add(btnDeleteAcc);
        
        JLabel lblAccountSettings = new JLabel("ACCOUNT SETTINGS");
        lblAccountSettings.setBounds(10, 176, 250, 26);
        lblAccountSettings.setHorizontalAlignment(SwingConstants.CENTER);
        lblAccountSettings.setFont(new Font("Tahoma", Font.BOLD, 12));
        frame.getContentPane().add(lblAccountSettings);
    }
    
    public void errorPane (String msg, String status) {
        JOptionPane.showMessageDialog(frame, msg, status, JOptionPane.ERROR_MESSAGE);
    }
    public void succMess (String smsg, String status2) {
        JOptionPane.showMessageDialog(frame, smsg, status2, JOptionPane.INFORMATION_MESSAGE);
    }
    public void clearTF() {
        tfNewUser.setText("");
        tfNewPass.setText("");
    }
    public void addReg(String regUser, String regPass) {
        try {
        BufferedWriter bw = new BufferedWriter(new FileWriter("Creds", true));
        bw.write(regUser+", "+regPass);
        bw.flush();
        bw.newLine();
        bw.close();
        succMess ("Account registered!", "SUCCESS");
        clearTF();
        }
        catch (Exception e) {
            errorPane("There is a problem with the data. Please input new data.", "ERROR" );
        }
        }
    public void deleteAcc() {
        try {
        String record;
        String regUser = tfNewUser.getText().toString();
        File tempCred = new File("Creds_temp");
        File cred = new File ("Creds");
        BufferedReader br = new BufferedReader(new FileReader(cred));
        BufferedWriter bw = new BufferedWriter(new FileWriter(tempCred));
        
        while((record = br.readLine())!=null) {
            if(record.contains(regUser))
                continue;
            
            bw.write(record);
            bw.flush();
            bw.newLine();
                
        }
        br.close();
        bw.close();
        
        cred.delete();
        tempCred.renameTo(cred);
        succMess ("Account Deleted!", "SUCCESS");
        }
        catch (Exception e) {
            errorPane("Cannot find account. Please register an account first.", "ERROR" );
        }
    }       
}

So assuming that the login file only deals with the authentication...所以假设登录文件只处理身份验证......

  1. Read the .txt file line by line (I'm using Java Scanner for convenience, but you could use FileReader or anything else as well)逐行读取.txt文件(为方便起见,我使用 Java Scanner,但您也可以使用 FileReader 或其他任何工具)
  2. Split each line by comma delimiters and store the data in a hash map用逗号分隔符分隔每一行并将数据存储在 hash map
  3. Compare whether the user input matches one比较用户输入是否匹配

In Login.java :Login.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;

public class Login {
  private HashMap<String, String> userData = new HashMap<String, String>();
  private String name;
  private String password;
  void readFile() {
    try {
      // read file
      File file = new File("passwords.txt"); // replace with file name!!
      Scanner reader = new Scanner(file);
      // loop through each line inside the file being read
      while (reader.hasNextLine()) {
        String str = reader.nextLine();
        String[] user = str.split(", "); // user[0] = anything before ", " and user[1] = anything after ", "
        userData.put(user[0], user[1]); // store username and password
      }
      reader.close(); // remember to close the reader
    } catch (FileNotFoundException e) {
      System.out.println("Something happened...");
      e.printStackTrace();
    }
  }
  public boolean loggedIn() {
    return password.equals(userData.get(name));
  }
  
  // constructor to execute on instance creation
  public Login(String name, String password) {
    // initialize data
    this.name = name;
    this.password = password;
    readFile();
  }
}

And pretend your user data file ( passwords.txt ) looks something like:假设您的用户数据文件 ( passwords.txt ) 看起来像这样:

Redman, 1234
Bob, $up3r-$ecur3
Rob, pls don't hack

Using the class is pretty easy:使用 class 非常简单:

Login attempt = new Login(username, password); // replace with requested variables as string
boolean success = attempt.loggedIn();

if(success) {
  // logged in successfully
} else {
  // incorrect username or password!
}

Working (only login) example.工作(仅登录)示例。

Hope that helps you get somewhere.希望能帮助你到达某个地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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