黑马程序员技术交流社区
标题:
notepad
[打印本页]
作者:
15044393192
时间:
2016-4-10 21:01
标题:
notepad
package cn.itcast.notepad.dao;
import java.util.*;
import java.io.*;
import cn.itcast.notepad.domain.Student;
import cn.itcast.notepad.utils.BookUtils;
public class StudentDaoImpl implements StudentDao {
private List<Student> stus;
public StudentDaoImpl() {
try {
stus = load();
} catch(Exception e) {
stus = new ArrayList<Student>();
}
}
public static List<Student> load() throws Exception {
ObjectInputStream ois = new ObjectInputStream(BookUtils.getInputStream("data/stus.dat"));
Object o = ois.readObject();
if(o != null) {
return (ArrayList<Student>)o;
}
return new ArrayList<Student>();
}
public void store() {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(BookUtils.getFile("data/stus.dat")));
oos.writeObject(stus);
} catch(Exception e) {
}
}
public void add(Student stu) {
stus.add(stu);
this.store();
}
public void delete(Student stu) {
stus.remove(stu);
this.store();
}
public void delete(int number) {
delete(selectByNumber(number));
this.store();
}
public void modify(Student stu) {
Student s = selectByNumber(stu.getNumber());
s.setName(stu.getName());
s.setAge(stu.getAge());
s.setSex(stu.getSex());
this.store();
}
public Student selectByNumber(int number) {
for(Student s : stus) {
if(s.getNumber() == number) {
return s;
}
}
return null;
}
public List<Student> selectByName(String name) {
List<Student> array = new ArrayList<Student>();
for(Student s : stus) {
if(name.equals(s.getName())) {
array.add(s);
}
}
return array;
}
public List<Student> selectByAge(int age) {
List<Student> array = new ArrayList<Student>();
for(Student s : stus) {
if(age == s.getAge()) {
array.add(s);
}
}
return array;
}
public List<Student> selectBySex(String sex) {
List<Student> array = new ArrayList<Student>();
for(Student s : stus) {
if(sex.equals(s.getSex())) {
array.add(s);
}
}
return array;
}
public List<Student> getAll() {
return stus;
}
public int getNumber() {
if(stus.size() == 0) {
return 1000;
}
return stus.get(stus.size() - 1).getNumber() + 1;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2