[英]Assistance on simple authentication system in Java
我編寫了一個非常簡單的程序,該程序從文本文件中讀取用戶名和密碼,其中用戶名和密碼用逗號分隔。 文本文件的內容包含以下內容
account.txt
亞歷克斯,1234
大衛5678
我的Java應用程序編寫如下
public class Authenticate {
public void signIn(String username, String password) throws IOException {
FileReader fr = new FileReader("location/accounts.txt");
BufferedReader br = new BufferedReader(fr);
while (true) {//read file line by line
String line = br.readLine();
if (line == null) {
break;
}
String splitByComma = ",";
String[] details = line.split(splitByComma);
String registeredUser = details[0];
String registeredPass= details[1];
if(username.equals(registeredUser) && password.equals(registeredPass)){
System.out.println("signed in successfully!");
}
else{
System.out.println("sign in failed");
}
}
br.close();
}
}
我的App類調用了該程序:
public class App {
public static void main(String[] args) throws IOException {
Register register = new Register("location/accounts.txt");
Authenticate auth = new Authenticate();
auth.signIn("David", "5678");
}
}
問題是例如當我在方法中傳遞“ Alex”“ 1234”時,輸出為
登錄成功!
登錄失敗
當我通過“ David”“ 5678”時,我得到
登錄失敗
登錄成功!
我希望應用程序根據輸入的憑據僅輸出一次“登錄成功”和“登錄失敗”。
非常感謝!
這意味着您將使用不同的值兩次調用您的方法。 檢查呼叫代碼(您尚未提供給我們)。
其他說明:
請不要考慮使用這種方式進行認真的身份驗證。 密碼至少應散列在文件中(例如,使用BCrypt )。 有許多框架提供了行業強度的身份驗證解決方案,您應該使用它們而不是“自己動手”。
您應該通過以下方式之一關閉資源:
1)在finally塊中:
BufferedReader br = null;
try {
br = new BufferedReader(...);
// do stuff
}
finally {
if (br != null) {
br.close();
}
}
2)使用Java 8 try-with-resources慣用法:
try (BufferedReader br = new BufferedReader(...)) {
// do stuff
}
(BufferedReader將由運行時環境自動關閉)
在上面的示例中,您可能應該在使用.equals
檢查值之前檢查輸入是否為空值。
首先搜索用戶名。 找到后,檢查密碼並退出循環:
public class Authenticate {
public void signIn(String username, String password) throws IOException {
try (
FileReader fr = new FileReader("location/accounts.txt");
BufferedReader br = new BufferedReader(fr);
) {
boolean success = false;
String line;
while ((line = br.readLine()) != null) {
String[] details = line.split(",");
String registeredUser = details[0];
if (registeredUser.equals(username)) {
String registeredPass = details[1];
success = registeredPass.equals(password);
break;
}
}
System.out.println(success ? "signed in successfully!" : "sign in failed");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.