java对象序列化流 将对象写入文件当中

对象序列化流可以写入对象和读取文件中的对象

本文主要讲解写入对象

我们先在项目的目录下创建两个类
text测试类和customException类 我们最后要将 customException类对象写入到文件当中

我们在customException中编写代码如下

import java.io.Serializable;

public class customException implements Serializable {
    
    
    private String name;
    private int age;

    public customException(String name,int age){
    
    
        this.name = name;
        this.age = age;
    }

    public void setName(String name){
    
    
        this.name = name;
    }
    public String getName(){
    
    
        return this.name;
    }
    public void setAge(int age){
    
    
        this.age = age;
    }
    public int getAge(){
    
    
        return this.age;
    }
}

这里 我们定义了两个属性 name 和 age 并给他们定义了 get和set方法
实现了Serializable 接口 这个是一定要的 你要是不实现Serializable 进行对象序列化就会报异常

然后我们定义了一个构造方法 接受两个参数
并赋值给name和age

然后我们在text测试类中编写

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class text {
    
    
    public static void main(String args[]) throws IOException {
    
    
        ObjectOutputStream cos = new ObjectOutputStream(new FileOutputStream("D:\\学习案例\\java\\目的地\\example.java"));
        customException cust = new customException("小猫猫",11);
        cos.writeObject(cust);
        cos.close();
    }
}

我们先创建了一个对象写入流ObjectOutputStream 参数是一个FileOutputStream实例化出来的一个文件对象 对应的文件在我电脑中是存在的
在这里插入图片描述
内容是空的
在这里插入图片描述
然后我们通过ObjectOutputStream 的writeObject将实力出来的customException对象写入到文件中 然后通过close释放资源

我们运行代码后 查看文件
在这里插入图片描述
我们的对象信息就写进去了 不用纠结看不懂 序列化流可以将这些信息读出来

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/127352336