java 序列化流

一、ObjectOutputStream 对象存储到硬盘

1、构造

new ObjectOutputStream(FileOutputStream对象)

2、方法

writeObject(对象)

3、注意

对象类需要实现 Serializable

二、ObjectInputStream 读取硬盘的对象

1、构造

new ObjectInputStream(FileInputStream对象)

2、方法

readObject()

三、案例

对象类

package com.wt.buffer;

import java.io.Serializable;

public class Person implements Serializable {
    private String name;
    private Integer age;

    public Person() {

    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

主类

package com.wt.buffer;

import java.io.*;
import java.util.ArrayList;

public class Demon07 {
    public static void main(String[] args) {
        // 存入
        // method();
        // 读取
        method1();

    }

    private static void method1() {
        try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("module3\\6.txt"))) {
            Object object = ois.readObject();
            System.out.println(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static void method() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("module3\\6.txt"));){
            ArrayList<Person> people = new ArrayList<>();
            people.add(new Person("tom", 12));
            people.add(new Person("小新", 8));
            people.add(new Person("广智", 40));
//            oos.writeObject(new Person("tom", 12));
            oos.writeObject(people);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

 

posted @ 2025-04-20 14:49  市丸银  阅读(6)  评论(0)    收藏  举报