什么是序列化?
所谓的序列化就是将对象流化,就是将对象变成字节。
如何实现序列化?
让某个类实现Serializable接口(标记性接口)。
将一个对象保存到文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Student implements Serializable{ private String Num; private String Name; private String Sex; public Student(String Num,String Name,String Sex){ this.Num = Num; this.Name = Name; this.Sex = Sex; } } public void objectToFile throws Exception{ FileOutputStream fos = new FileOutputStream("X:\\xxx.xxx"); ObjcetOutputStream oos = new ObjcetOutputStream(fos); Student student1 = new Student("123","王五","男"); oos.writeObject(student1); oos.close(); fos.close(); }
|
从文件中读取一个对象
1 2 3 4 5 6 7 8 9 10 11 12
| public void readFromFile() throws Exception{ FileInputStream fis = new FileInputStream("X:\\xxx.xxx"); ObjectInputStream ois = new ObjectInputStream(fis); Student student2 = (Student)ois.readObject(); System.out.println(student2); ois.close(); fis.close(); }
|