Java 对象流和序列化

 

对象流有两个类:

  (1)ObjectOutputStream:将对象的基本数据类型和图形进行序列化

  (2)ObectInputStream:对已保存的序列化文件进行反序列化

 

序列化一组对象可使用对象数组的方式。

transient关键字:

  若某个成员变量被transient修饰,那么当对象被序列化的时候,该变量不会被保存。

 

代码示例:

package com.seven.javaSE;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class ObejctSerializable {
    public static void main(String[] args) {
        saveObejct();
        readObject();
    }
    
    //将对象序列化,保存在本地
    public static void saveObejct() {
        Animal cat = new Animal(1,"中国",2);
        try {
            OutputStream out = new FileOutputStream("c:/TestFile/cat.obj");
            ObjectOutputStream oos = new ObjectOutputStream(out);
            oos.writeObject(cat);
            oos.close();
            System.out.println("对象序列化完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //将对象反序列化,读取被保存的对象
    public static void readObject() {
        try {
            InputStream in = new FileInputStream("C:/TestFile/cat.obj");
            ObjectInputStream ois = new ObjectInputStream(in);
            Animal cat = (Animal)ois.readObject();
            System.out.println(cat);
            System.out.println("对象反序列化成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


/*
 * 一个类对象要想要保存在物理介质或在网络上传输,必须要实现Serializable接口
 * 此接口是一个标记接口,里面没有任何内容
 */
class Animal implements Serializable{

//    private static final long serialVersionUID = 1L;
    private int id;
    private String address;
    private int age;
    
    public Animal(int id, String address, int age) {
        super();
        this.id = id;
        this.address = address;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Animal [id=" + id + ", address=" + address + ", age=" + age + "]";
    }
    
}

 

posted @ 2022-06-17 20:35  藤原豆腐渣渣  阅读(56)  评论(0编辑  收藏  举报