通过Java把序列化对象存入json文件中

110 篇文章 0 订阅
95 篇文章 0 订阅

在开发中用到将用户信息保存到本地的json文件中,特此记录一下

实际开发中并不是所有的数据都要和数据库打交道的,比如用户第一次注册的信息是在数据库中,但是当第二次登录时候就从json文件中去查找相应的数据,数据库数据更新的时候确保json文件中的数据与数据库是一致的,在这里json文件起到了redis等中间缓存数据库的作用,避免过多的去操作数据库,记得以前看到过,这样说的,数据库连接的时间远大于数据库执行SQL语句的时间,所以延伸出来很多的办法去解决这一缺陷。

import com.bmsj.pojo.UserPojo;

import java.io.*;
import java.util.UUID;

public class ObjectJson {
    /**
     * 实现对象序列化的追加
     * @param path
     * @param user
     * @throws IOException
     */
    public static void writeObjectJson(String path, UserPojo user) throws IOException {
        File file = new File(path);
//        定义一个用来判断文件是否需要裁掉头
        boolean isexist = false;
//        文件是否存在
        if (file.exists()){
            isexist = true;
            FileOutputStream fo = new FileOutputStream(file, true);
            ObjectOutputStream oos = new ObjectOutputStream(fo);
            long pos = 0;
            if (isexist){.
//                追加的时候去掉头
                pos = fo.getChannel().position() -4 ;
                fo.getChannel().truncate(pos);
            }
            oos.writeObject(user);
            System.out.println("追加成功");
        }else {
            file.createNewFile();
            FileOutputStream fo = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fo);
            oos.writeObject(user);
            oos.close();
            System.out.println("首次对象序列化成功!");
        }
    }

    /**
     * 实现从文件中读取多个对象
     * @param path
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static  void readObjectJson(String path) throws IOException, ClassNotFoundException {
        File file = new File(path);
        if (file.exists()){
            ObjectInputStream ois ;
            FileInputStream fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
//            代表文件是否还有内容
            while (fis.available() > 0){
//                从流中读出来
                UserPojo user  = (UserPojo) ois.readObject();
                System.out.println(user.getUsername());
            }
            ois.close();
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        UserPojo userPojo = new UserPojo();
        userPojo.setId(UUID.randomUUID().toString().replace("-",""));
        userPojo.setUsername("9527");
        userPojo.setPassword("9527");
        userPojo.setStatus(1);
        writeObjectJson("F:\\userPojo.json",userPojo);
        readObjectJson("F:\\userPojo.json");
    }
}

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值