【发布时间】:2021-03-16 16:44:47
【问题描述】:
我正在尝试读取这种格式的 txt 文件(不包括标题):
firstname lastname username password
John Doe $1234567 $123
Eden Hask $1234576 $12345
最近一次登录(Eden)总是有效,但不是之前的一次(John)。 出于某种原因,分隔符将包含所有细节,直到下一个 $。 我应该如何让我的分隔符在密码后停止。
The user name is_1234567 and the password is_123
Eden Hask!
The user name is_1234576 and the password is_12345!
这是完整的代码。
public void login() throws FileNotFoundException{
File file = new File("file.txt");
Scanner read = new Scanner(file);
found = false;
read.useDelimiter("(\s*\\$)");
try {
Scanner keyboard = new Scanner(System.in);
System.out.print("Username: ");
String username = keyboard.nextLine();
System.out.print("Password: ");
String passwordField = keyboard.nextLine();
while(read.hasNext()){
String user = read.next();
String pass = read.next();
System.out.println("The user name is_" + user + " and the password is_" + pass + "!\n");
if(user.trim().equals(username) && pass.trim().equals(passwordField)){
boolean found = true;
break;
}
}
if(found){
return true;
}
else {
return false;
}
read.close();
}catch(Exception e){
throw e;
}
};
【问题讨论】:
-
为什么不直接使用制表符 ("\t") 来分隔字段?