IO流对象处理流

对象处理流

1.序列化过程

package com.wang.object;

import java.io.*;

public class objectout {
    public static void main(String[] args) throws IOException {
        String path="d:/hello.txt";
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));
        objectOutputStream.writeInt(100);
        objectOutputStream.writeBoolean(true);
        objectOutputStream.writeUTF("我是牛逼");
        objectOutputStream.writeObject(new dog("赵心梦",5));
        objectOutputStream.close();
    }
}
class  dog implements Serializable
{
    private  String name;
    private  int id;

    public dog(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

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

2.反序列化

package com.wang.object;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class obgeinput {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String path="d:/hello.txt";
        ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(path));
        System.out.println(objectInputStream.readInt());
        System.out.println(objectInputStream.readBoolean());
        System.out.println(objectInputStream.readUTF());
        Object dog=objectInputStream.readObject();
        System.out.println(dog.getClass());
        System.out.println(dog);
        dog dog2 =(dog)dog;
        System.out.println((dog2.getName()));
        objectInputStream.close();
    }
}

注意事项:

读写顺序要一致

序列化的类中要实现Serializable接口

序列化对象时static和transient修饰的对象无法序列化

序列化具有可继承性

posted @   jinnice  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示