java_对象序列化

  • 对象序列化(serializable)

序列化读ObjectInputStream  ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));

序列化写: ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));

序列化对象参数为I/O字节流读写对象。

1.将对象序列化写到本地

新建学生类实现序列化接口,当对象中某一个属性或方法不需要序列化时,在属性或方法前加:transient.

import java.io.Serializable;
public class Student implements Serializable {
private String name;
transient private int age; //某一个属性不需要序列化时加:transient
private String id;
public void eat(){
System.out.println("吃吃");
}
//这里需要添加set和get方法

}

创建对象,实现对象序列化写到本地文件ggg.txt

@Test
public void test12(){
Student stu = new Student();
stu.setName("序列化测试");
stu.setAge(20);
stu.setId("21432423");
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));
oos.writeObject(stu); //将一个对象写入到本地

} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:�� sr com.lanou.Studenta��N0�� L idt Ljava/lang/String;L nameq ~ xpt 21432423t 序列化测试

2.反序列化读,将本地文件ggg.txt文件反序列化读回计算机
@Test
public void test13(){

//将序列化好的对象,读回计算机
//反序列化

ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));
Object o=ois.readObject();
System.out.println(o);

} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:
Student{name='序列化测试', age=0, id='21432423'}
 
Process finished with exit code 0
 

                                                                                     

猜你喜欢

转载自www.cnblogs.com/zhouchangyang/p/10645065.html