java.io对象_JavaIO(七) 对象流

对象流是用于将内存中的对象序列化后存于文件中,或将文件中的数据反序列化为对象

新建一个Person类,一个类要想序列化必须实现Serializable 接口

package com.mike.io.eg;

import java.io.Serializable;

/**

* @author mike

* @date 2020-11-26

* @desc 被序列化对象类

*/

public class Person implements Serializable {

private int id;

private String name;

private int age;

public Person() {

}

public Person(int id,String name,int age) {

this.id = id;

this.name = name;

this.age = age;

}

}

ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。

主要有一个常用方法: void writeObject(Object obj) 将对象写入文件

package com.mike.io.eg;

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.io.FileOutputStream;

/**

* @author mike

* @date 2020-11-28

* @desc 测试序列化对象

*/

public class ObjectOutputStreamDemo {

public static void main(String[] args) {

//定义对象流

ObjectOutputStream oos = null;

//创建对象流

try {

oos = new ObjectOutputStream(new FileOutputStream("F:\\person.txt"));

oos.writeObject(new Person(10001,"mike",26));

oos.writeObject(new Person(10002,"jeef",23));

oos.flush();

System.out.println("序列化成功");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

oos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。

主要有一个方法: Object readObject() 将对象从文件读出

package com.mike.io.eg;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.FileInputStream;

/**

* @author mike

* @date 2020-11-28

* @desc 测试对象反序列化

*/

public class ObjectInputStreamDemo {

public static void main(String[] args) {

//定义反序列化对象

ObjectInputStream ois = null;

try {

ois = new ObjectInputStream(new FileInputStream("F:\\person.txt"));

Person person1 = (Person) ois.readObject();

Person person2 = (Person) ois.readObject();

System.out.println(person1);

System.out.println(person2);

System.out.println("反序列化成功");

}catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

} finally {

if (ois != null) {

try {

ois.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

输出结果

adc633822f3a33030951cdac9d30c130.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值