|
|
package auth;
|
|
|
import java.io.BufferedReader;
|
|
|
import java.io.FileReader;
|
|
|
import java.util.*;
|
|
|
import java.io.IOException;
|
|
|
public class UserManager {
|
|
|
private List<User> users = new ArrayList<>();
|
|
|
public static int line_num= 0;
|
|
|
public UserManager() {
|
|
|
// 要读取的文件路径
|
|
|
String filePath = "user.txt";
|
|
|
// 调用方法读取文件并获取三个数据列表
|
|
|
DataLists dataLists = readDataFile(filePath);
|
|
|
for(int i=0;i<line_num;i++) {
|
|
|
users.add(new User(dataLists.list1.get(i), dataLists.list2.get(i), dataLists.list3.get(i)));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
public User login(String username, String password) {
|
|
|
for (User user : users) {
|
|
|
if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
|
|
|
return user;
|
|
|
}
|
|
|
}
|
|
|
return null;
|
|
|
}
|
|
|
static class DataLists {
|
|
|
List<String> list1;
|
|
|
List<String> list2;
|
|
|
List<String> list3;
|
|
|
|
|
|
DataLists(List<String> list1, List<String> list2, List<String> list3) {
|
|
|
this.list1 = list1;
|
|
|
this.list2 = list2;
|
|
|
this.list3 = list3;
|
|
|
}
|
|
|
}
|
|
|
public static DataLists readDataFile(String filePath) {
|
|
|
List<String> list1 = new ArrayList<>();
|
|
|
List<String> list2 = new ArrayList<>();
|
|
|
List<String> list3 = new ArrayList<>();
|
|
|
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
|
|
|
String line;
|
|
|
int lineNumber = 1;
|
|
|
// 逐行读取
|
|
|
while ((line = br.readLine()) != null) {
|
|
|
// 去除首尾空格
|
|
|
line = line.trim();
|
|
|
|
|
|
// 跳过空行
|
|
|
if (line.isEmpty()) {
|
|
|
continue;
|
|
|
}
|
|
|
// 分割行数据,这里假设使用空格分隔
|
|
|
// 如果是其他分隔符(如逗号、制表符),请修改正则表达式
|
|
|
String[] parts = line.split("\\s+");
|
|
|
if (parts.length != 3) {
|
|
|
System.out.println("警告: 第" + lineNumber + "行数据格式不正确,需要3个数据,实际有" + parts.length + "个");
|
|
|
lineNumber++;
|
|
|
continue;
|
|
|
}
|
|
|
// 将三个数据分别添加到对应的列表
|
|
|
list1.add(parts[0]);
|
|
|
list2.add(parts[1]);
|
|
|
list3.add(parts[2]);
|
|
|
lineNumber++;
|
|
|
}
|
|
|
line_num=lineNumber-1;
|
|
|
return new DataLists(list1, list2, list3);
|
|
|
}catch (IOException e) {
|
|
|
System.out.println("读取文件时发生错误: " + e.getMessage());
|
|
|
e.printStackTrace();
|
|
|
return null;
|
|
|
}
|
|
|
}
|
|
|
}
|