[英]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.