在开发中用到将用户信息保存到本地的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");
}
}