对象流序列化与反序列化

package Serialize;

import java.io.*;

/**

  • 序列化与反序列化
  • 注意:对象的序列化与反序列化使用的类要严格一致,包名,类名,类机构等等所有都要一致
    */

public class Test {
public static void main(String[] args) {
try {
// Test.testSerialize(“F:\Java_project_new\src\Serialize\tt.txt”);
Test.testDeserialize(“F:\Java_project_new\src\Serialize\tt.txt”);
} catch (Exception e) {
e.printStackTrace();
}

}

/**
 * 对象的序列化
 */
//F:\Java_project_new\src\Serialize\tt.txt
public static void testSerialize(String output) throws Exception {
    //定义对象的输出流,把对象的序列化之后的流放到指定的文件中
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(output));
    Serialize ser = new Serialize();
    ser.name="tom";
    ser.age=18;
    out.writeObject(ser);  //将对象写入到内存
    out.flush(); //将对象刷到硬盘
    out.close();
}

/**
 * 对象的反序列化
 */
public static void testDeserialize(String Input) throws Exception{
    //创建对象输入流 从指定的文件中把对象序列化后的流读取出来
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(Input));

// Object obj = in.readObject();
// Serialize ser = (Serialize)obj;
Serialize ser = (Serialize) in.readObject();
System.out.println(ser.name);
System.out.println(ser.age);
in.close();
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值