1、序列化和反序列化分别是什么?
2、序列化和反序列化分别有什么意义?
3、序列化和反序列化怎么用?
1、序列化是将java对象转换成字节文件的过程;
反序列化是将字节文件转换成java对象的过程。
2、序列化是为了将内存中的文件永久保存;
序列化是为了将文件进行网络交换。
3、下面是一个 序列化和反序列化的案例
package main;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//对象的序列化和反序列化 入门
public class Test {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
// SerializePerson();
Person pe = DeserializePerson();
System.out.println("age is : " + pe.getAge());
System.out.println("name is : " + pe.getName());
System.out.println("sex is : " + pe.getSex());
}
public static void SerializePerson() throws IOException {
Person pe = new Person();
pe.setAge("22");
pe.setName("Ban");
pe.setSex("man");
FileOutputStream fos = new FileOutputStream("E:/test.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(pe);
oos.close();
System.out.println("serialize successfully!!");
}
public static Person DeserializePerson() throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream("E:/test.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person pe = (Person) ois.readObject();
return pe;
}
}
附:实体类
package main;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
tips:实体类必须实现serializable接口 并且 写上 private static final long serivalVersionUID = 1L;
不然会报错 NoSerival.....的错
版权声明:本文为博主原创文章,未经博主允许不得转载。