gpt4 book ai didi

java - 如何将带有分隔符的文本文件读入数组并将数组元素存储在变量中?

转载 作者:行者123 更新时间:2023-12-02 09:17:14 26 4
gpt4 key购买 nike

我试图制作一个登录页面,尝试将用户的数据导入到数组中。然后将输入的用户名和密码与数组中存储的用户名(array[1])和密码(array[2])进行匹配。请帮助我。

文本文件:

72|shawn31|123456|Shawn 
Brown|KL|shwanbrown@gmail.com|Administrator|01234567|1|1|1970

代码:

public void openFile() {
try {
readCodes = new Scanner(new File("C:\\Users\\april\\Documents\\NetBeansProjects\\OODJ\\user.txt"));
} catch (Exception e) {
System.out.println("Could not locate the data file");
}
}

public void readFile() {
while (readCodes.hasNextLine()) {
String d = readCodes.nextLine();
StringTokenizer st = new StringTokenizer(d, "|");
String[] userDetails = new String[st.countTokens()];
int index = 0;
while (st.hasMoreTokens()) {
userDetails[index] = (String) st.nextElement();
index++;
}
}
userDetails[0] = id;
userDetails[1] = username;
userDetails[2] = password;
userDetails[3] = name;
userDetails[4] = address;
userDetails[5] = email;
userDetails[6] = role;
userDetails[7] = number;
userDetails[8] = day;
userDetails[9] = month;
userDetails[10] = year;
}

public boolean login(String uname, String pass) {
boolean success = false;
readFile();
if (userDetails[1].equals(uname) && userDetails[2].equals(pass)) {
success = true;
}
return success;
}

最佳答案

主要问题是您没有将数组值分配给字段,反之亦然。

public void readUser() {
try {
Path path = Paths.get("C:\\Users\\april\\Documents\\NetBeansProjects\\OODJ\\user.txt");
Files.lines(path, Charset.defaultCharset())
.map(line -> line.split("\\|"))
.filter(arr -> arr.length == 11)
.limit(1)
.forEach(arr -> {
id = arr[0];
username = arr[1];
password = arr[2];
name = arr[3];
address = arr[4];
email = arr[5];
role = arr[6];
number = arr[7];
day = arr[8];
month = arr[9];
year = arr[10];
});
} catch (Exception e) {
System.out.println("Could not locate the data file");
}
}

一个让它变得更加优雅的想法,并在此基础上进行扩展:

class User {
String id;
String username;
String password;
String name;
String address;
String email;
String role;
String number;
String day;
String month;
String year;
}

public List<User> readUsers() throws IOException {
Path path = Paths.get("C:\\Users\\april\\Documents\\NetBeansProjects\\OODJ\\users.txt");
return Files.lines(path, Charsets.defaultCharset())
.map(line -> line.split("\\|"))
.filter(arr -> arr.length == 11)
.map(arr -> {
User user = new User();
user.id = arr[0];
user.username = arr[1];
user.password = arr[2];
user.name = arr[3];
user.address = arr[4];
user.email = arr[5];
user.role = arr[6];
user.number = arr[7];
user.day = arr[8];
user.month = arr[9];
user.year = arr[10];
return user;
})
.collect(Collectors.toList());
}

关于java - 如何将带有分隔符的文本文件读入数组并将数组元素存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58910685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com