繁体   English   中英

如何使用 BufferedReader 登录 function?

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

我是一年级编程学生,我的任务是使用 Java Swing(应用程序窗口)和 BufferedReader+Writer 制作一个登录和注册程序。 我现在可以通过 BWriter 将用户名和密码写入文本文件,但是我不知道如何让登录读取文本文件,并且只有在他们尊重的 TextField 中输入的用户名和密码与我写入的用户名和密码匹配时才登录文本文件。 (作为参考,在我从注册部分写入假定的用户名和密码后,文本文件看起来像这样: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" );
        }
    }       
}

所以假设登录文件只处理身份验证......

  1. 逐行读取.txt文件(为方便起见,我使用 Java Scanner,但您也可以使用 FileReader 或其他任何工具)
  2. 用逗号分隔符分隔每一行并将数据存储在 hash map
  3. 比较用户输入是否匹配

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();
  }
}

假设您的用户数据文件 ( passwords.txt ) 看起来像这样:

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

使用 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!
}

工作(仅登录)示例。

希望能帮助你到达某个地方。

暂无
暂无

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

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