package cn.itcast.notepad.dao;
import java.io.*;
import java.util.*;
import cn.itcast.notepad.domain.User;
import cn.itcast.notepad.utils.BookUtils;
public class UserDaoImpl implements UserDao {
private List<User> users;
public UserDaoImpl() {
try {
users = load();
} catch(Exception e) {
users = new ArrayList<User>();
}
}
public boolean login(User user) {
return users.contains(user);
}
public boolean updatePwd(User user) {
User u = getUserByName(user.getName());
if(u == null) {
return false;
}
u.setPassword(user.getPassword());
this.store();
return true;
}
public boolean regist(User user) {
User u = getUserByName(user.getName());
if(u != null) {
return false;
}
users.add(user);
this.store();
return true;
}
private User getUserByName(String name) {
for(User u : users) {
if(u.getName().equals(name)) {
return u;
}
}
return null;
}
public static ArrayList<User> load() throws Exception {
ObjectInputStream ois = new ObjectInputStream(BookUtils.getInputStream("data/users.dat"));
return (ArrayList<User>)ois.readObject();
}
public void store() {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(BookUtils.getFile("data/users.dat")));
oos.writeObject(users);
} catch(Exception e) {
e.printStackTrace();
}
}
} |
|