什么是java序列化?如何实现java序列化?

来源:互联网 发布:什么是网络攻防大赛 编辑:程序博客网 时间:2024/05/16 15:12
  1. java序列化就是处理对象流机制,所谓对象流就是将对象流化,可以对流化的对象进行读写,也可以将流化后的后的对象传输于网络之间。
  2. 序列化的实现:将需要序列化的对象实现serializable接口,然后使用一个输出流(如FileOutputStream)来构建一个ObjectOutputStream(对象流)对象,然后使用ObjectOutputStream对象的WriteObject(Object obj)方法就可以将参数obj保存,恢复的话用输入流。
  3. 需要序列化的对象只需要实现serializable接口即可,该接口是一个mini接口,无需实现具体方发,implements serializable只是为了标注该对象是可以序列化的。
    import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class Cat implements Serializable{private String name;public Cat (){this.name = "new name";}public void setName(String name){this.name = name;}public String getName(){return this.name;}public static void main(String[] args){Cat cat = new Cat();try{FileOutputStream fos = new FileOutputStream("catDemo.out");ObjectOutputStream oos = new ObjectOutputStream(fos);System.out.println(cat.getName());cat.setName("My Cat");oos.writeObject(cat);oos.close();} catch(Exception ex) {ex.printStackTrace();}try{FileInputStream fis = new FileInputStream("catDemo.out");ObjectInputStream ois = new ObjectInputStream(fis);cat = (Cat)ois.readObject();System.out.println(cat.getName());ois.close();} catch(Exception ex){ex.printStackTrace();}}}

0 0
原创粉丝点击