[英]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" );
}
}
}
所以假設登錄文件只處理身份驗證......
.txt
文件(為方便起見,我使用 Java Scanner,但您也可以使用 FileReader 或其他任何工具)在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.