CoreJava/exp11/AccountManager.java

91 lines
2.4 KiB
Java
Raw Normal View History

2024-05-15 20:49:31 +08:00
package exp11;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class AccountManager {
private String userinfoPath = "userinfo.txt";
private ArrayList<Account> getAccounts() {
File userinfo = new File(userinfoPath);
ArrayList<Account> accounts = new ArrayList<>();
try{
BufferedReader reader = new BufferedReader(new FileReader(userinfo));
String line;
while ((line=reader.readLine()) != null) {
String[] strs = line.split(",");
Account account = new Account(strs[0], strs[1]);
accounts.add(account);
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
return accounts;
}
Account getAccount(String username) {
Account account = null;
ArrayList<Account> accounts = getAccounts();
for (Account a : accounts) {
if(a.getUserName() == username) {
account = a;
}
}
return account;
}
public boolean userIsExist(String username) {
ArrayList<Account> accounts = getAccounts();
for (Account account : accounts) {
if (username == account.getUserName()){
return true;
}
}
return false;
}
public void addUser(Account account) {
if (userIsExist(account.getUserName())) {
System.out.println("用户已存在!");
}else {
File userinfo = new File(userinfoPath);
try{
FileWriter writer = new FileWriter(userinfo, true);
writer.write(account.toString());
writer.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
boolean usernameVerify(String username) {
if(username.matches("a-zA-Z")){
return true;
}else {
System.out.println("用户名不合法");
return false;
}
}
boolean accountVerify(String username, String password) {
Account account = getAccount(username);
if ((account.getUserName()==username) && (account.getPassword()==password)){
return true;
}
return false;
}
}