-
Notifications
You must be signed in to change notification settings - Fork 0
/
StudentDao.txt
102 lines (94 loc) · 2.49 KB
/
StudentDao.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package vn.viettuts;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* StudentDao class
*
* @author viettuts.vn
*/
public class StudentDao {
private static final String STUDENT_FILE_NAME = "student.txt";
/**
* save list student to file
*
* @param studentList: list student to save
*/
public void write(List<Student> studentList) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(new File(STUDENT_FILE_NAME));
oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeStream(fos);
closeStream(oos);
}
}
/**
* read list student from file
*
* @return list student
*/
public List<Student> read() {
List<Student> studentList = new ArrayList<>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(STUDENT_FILE_NAME));
ois = new ObjectInputStream(fis);
studentList = (List<Student>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
closeStream(fis);
closeStream(ois);
}
return studentList;
}
/**
* close input stream
*
* @param is: input stream
*/
private void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* close output stream
*
* @param os: output stream
*/
private void closeStream(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}