package com.mepu; import org.junit.Test; import java.io.*; /** * @author: 艾康 * @date: 2020/1/1 14:29 * @description: TODO * @modifiedBy: * @version: 1.0 * 对象流的序列化与反序列化 */ public class ObjectIOTest { /* 序列化 */ @Test public void test1(){ ObjectOutputStream objectOutputStream = null; try { //创建字节流对象 FileOutputStream fileOutputStream = new FileOutputStream("object.dat"); //创建对象流 objectOutputStream = new ObjectOutputStream(fileOutputStream); //存储对象,对象需要满足可序列化条件,所有用到的类实现Serializable接口,不能序列化static修饰的变量 // 新增属性序列版本号:public static final long serialVersionUID=自定义值L; objectOutputStream.writeObject(new String("北京北京")); objectOutputStream.flush();//刷新 } catch (IOException e) { e.printStackTrace(); } finally { //关闭流 try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 反序列化 */ @Test public void test2() { ObjectInputStream objectInputStream = null; Object o = null; try { //创建文件对象 FileInputStream fileInputStream = new FileInputStream("object.dat"); //创建对象流 objectInputStream = new ObjectInputStream(fileInputStream); //读取 o = objectInputStream.readObject(); System.out.println(o); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { //关闭流 try { objectInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
原文地址:https://www.cnblogs.com/aikang525/p/12128975.html
时间: 2024-11-25 19:25:17