JAVA序列化和反序列化(到文件或者数据库)


前言

在某种情况下,需要考虑一些安全问题和数据对象的使用问题,这时候就可以用序列化的技术来进行数据存储。


一、序列化的好处

  1. 操作过程数据不可见,保证安全。
  2. 直接存储对象,后续操作方便。

二、实现

1.序列化到文件和数据库

代码如下(示例):

package com.student.serializable;

import com.student.SpringbootStart;
import com.student.mapper.StudentInfoMapper;
import com.student.model.StudentAddress;
import com.student.model.StudentInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Base64Utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Create by zjg on 2023/1/31
 */
@RunWith(SpringRunner.class) //作用:让当前类在容器环境下进行测试
@SpringBootTest(classes = SpringbootStart.class)//作用:声明当前类是springboot的测试类并且获取入口类上的相关信息 SpringBootApplication是入口类类名
public class SerializableTest {
    @Autowired
    private StudentInfoMapper studentInfoMapper;
    @Test
    public void test(){
        objectToDatabase();
    }

    /**
     * 把对象序列化到文件中
     */
    public void objectToFile(){
        //1.准备数据
        StudentInfo s1=new StudentInfo();
        s1.setId("1");
        s1.setName("张三");
        StudentInfo s2=new StudentInfo();
        s2.setId("2");
        s2.setName("李四");
        // 2.使用对象字节输出流包装字节输出流
        ObjectOutputStream oos = null;
        try {
            String name="F:\\test\\student.txt";
            oos= new ObjectOutputStream(new FileOutputStream(name));
            // 3.调用序列化方法, 把对象写到文件当中去
            System.out.println(s1);
            System.out.println(s2);
            oos.writeObject(s1);
            oos.writeObject(s2);
            System.out.println(name+"写入完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 4.释放资源
            try {
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对象从文件中反序列化出来
     */
    public void objectFromFile(){
        // 1.使用对象字节输入流包装字节输入流
        ObjectInputStream ois = null;
        try {
            String name="F:\\test\\student.txt";
            ois= new ObjectInputStream(new FileInputStream(name));
            // 2.调用反序列化方法, 把数据从文件读取到对象中
            StudentInfo s1= (StudentInfo) ois.readObject();
            StudentInfo s2= (StudentInfo) ois.readObject();
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(name+"读取完成!");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            // 3.释放资源
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 把对象序列化到数据库
     */
    public void objectToDatabase(){
        //1.准备数据
        String id="123";
        StudentAddress s1=new StudentAddress();
        s1.setAddress("金江华庭北区1号楼");
        StudentAddress s2=new StudentAddress();
        s2.setAddress("龙门天越14号楼");
        // 2.使用对象字节输出流包装字节输出流
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos=null;
        try {
            baos=new ByteArrayOutputStream();
            oos= new ObjectOutputStream(baos);
            // 3.调用序列化方法, 写入数据库
            System.out.println(s1);
            System.out.println(s2);
            oos.writeObject(s1);
            oos.writeObject(s2);
            StudentInfo studentInfo=new StudentInfo();
            studentInfo.setId(id);
            studentInfo.setName("zjg");
            studentInfo.setIdType("1");
            studentInfo.setIdNumber("372901");
            studentInfo.setAddress(Base64Utils.encodeToString(baos.toByteArray()));
            System.out.println(studentInfo);
            studentInfoMapper.insert(studentInfo);
            System.out.println("写入完成!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 4.释放资源
            try {
                baos.flush();
                baos.close();
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 对象从数据库中反序列化出来
     */
    public void objectFromDatabase(){
        //1.准备数据
        int id=123;
        // 2.使用对象字节输入流包装字节输入流
        ObjectInputStream ois = null;
        try {
            // 3.从数据库查询回来,反序列化对象
            StudentInfo studentInfo=studentInfoMapper.selectByPrimaryKey(id);
            System.out.println(studentInfo);
            ois= new ObjectInputStream(new ByteArrayInputStream(Base64Utils.decodeFromString(studentInfo.getAddress())));
            StudentAddress s1= (StudentAddress) ois.readObject();
            StudentAddress s2= (StudentAddress) ois.readObject();
            System.out.println(s1);
            System.out.println(s2);
            System.out.println("读取完成!");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            // 4.释放资源
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


总结

序列化主要借助于io包下ObjectInputStream和ObjectOutputStream流来完成对数据对象的序列化操作。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值