java序列化与反序列化
序列化:将对象写入到IO流中
反序列化:从IO流中恢复对象
意义:序列化机制允许将实现序列化的Java对象转换位字节序列,这些字节序列可以保存在磁盘上,或通过网络传输,以达到以后恢复成原来的对象。序列化机制使得对象可以脱离程序的运行而独立存在。
使用场景:所有可在网络上传输的对象都必须是可序列化的,所有需要保存到磁盘的java对象都必须是可序列化的。
这里只记录磁盘操作,等学了net再补上。
- 如果需要将某个对象保存到磁盘上或者通过网络传输,那么这个类应该实现Serializable接口或者Externalizable接口之一。Externalizable还有一些其他详细有个大佬写的挺好的look here
封装成方法:
package IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class LXLH {
public static void main(String[] args) {
Student3 s3 = new Student3(50);
File file = new File("D:\\tt.txt");
try {
Xuliehua(s3,file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("-------");
Student2 s4=null;
try {
s4 = (Student2)fanxuliehua(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(s4);
}
private static Object fanxuliehua(File file) throws FileNotFoundException, IOException, ClassNotFoundException{//反序列化文件----对象
ObjectInputStream ois=null;
ois = new ObjectInputStream(new FileInputStream(file));
Object obj=null;
obj = ois.readObject();
ois.close();
return obj;
}
private static void Xuliehua(Object s,File file) throws FileNotFoundException, IOException {
//序列化- - -把对象--写入文件
ObjectOutputStream oos=null;
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(s);
oos.close();
}
}
class Student3 implements Serializable {
private static final long serialVersionUID = 1L;
int Computer;
public Student3(int computer) {
super();
Computer = computer;
}
public int getComputer() {
return Computer;
}
public void setComputer(int computer) {
Computer = computer;
}
@Override
public String toString() {
return "Student2 [Computer=" + Computer + "]";
}
}
- 注意:
- 序列化同一对象,并不会将此对象序列化多次得到多个对象。
- transient:不需要属性用这个关键字。
- 重写writeObject与readObject方法可以实现定制需求,比如加密。但 相应的readObject需要相反的规则反序列化
- 类的成员不是基本类型,也不是String类型,那这个引用类型也必须是可序列化的;否则,会导致此类不能序列化。
- 反序列化并不会调用构造方法。反序列的对象是由JVM自己生成的对象,不通过构造方法生成。
- 将多个(相同或者不同)对象序列化到同一文件中:将多个对象保存在一个list中,然后将list当作一个对象存入到文件中(list已经实现了Serializable接口)
Student3 s3 = new Student3(50);
Student4 s4 = new Student4(60);
List<Object> list= new ArrayList<Object>();
list.add(s3);
list.add(s4);
//省序列化
ObjectInputStream oi=new ObjectInputStream(new FileInputStream(new File(file)));
List getlist=(List)oi.readObject();
System.out.println((Student3)getlist.get(0));
System.out.println((Student4)getlist.get(1));