You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* 用户仓库的内存实现。
* 在程序启动时,从文件中加载所有用户账户。
*/
public class UserRepository implements IUserRepository {
private final Map<String, User> userDatabase = new ConcurrentHashMap<>();
public UserRepository() {
// 从文件中加载用户数据
loadUsersFromFile();
}
/**
* 从指定的文本文件中加载用户信息。
* 文件的每一行应遵循 "username,password,level" 格式。
*/
private void loadUsersFromFile() {
// 使用 try-with-resources 语句确保 BufferedReader 被正确关闭
try (BufferedReader reader = new BufferedReader(new FileReader("./account/account.txt"))) {
String line;
// 逐行读取文件
while ((line = reader.readLine()) != null) {
// 使用逗号分割每行的数据
String[] parts = line.split(",");
// 确保每行都有三部分:用户名、密码和用户级别
if (parts.length == 3) {
String username = parts[0].trim();
String password = parts[1].trim();
String level = parts[2].trim();
userDatabase.put(username, new User(username, password, level));
}
}
} catch (IOException e) {
// 如果文件未找到或发生其他IO错误打印错误信息
System.err.println("从文件加载用户数据时出错: " + "./account/account.txt");
}
}
/**
* 根据用户名查找用户。
*
* @param username 要查找的用户的用户名。
* @return 如果找到用户则返回一个包含该用户的Optional
* 如果未找到则返回一个空的Optional
*/
@Override
public Optional<User> findByUsername(String username) {
return Optional.ofNullable(userDatabase.get(username));
}
}