先创建一个 User 实体类做测试
public class User implements Serializable { // private static final long serialVersionUID = -1568730003971173026L; // @Protobuf(fieldType = FieldType.INT32) private Integer userId; // @Protobuf(fieldType = FieldType.STRING) private String userName; // @Protobuf(fieldType = FieldType.DATE) private Date userBirth; public Date getUserBirth() { return userBirth; } public void setUserBirth(Date userBirth) { this.userBirth = userBirth; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", userBirth=" + userBirth + '}'; } }
一、Java 自带序列化
- 序列化方法
public static void serialize() throws IOException { User user = new User(); user.setUserId(1); user.setUserName("序列化"); user.setUserBirth(new Date()); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user")); oos.writeObject(user); oos.flush(); oos.close(); }
- 反序列化方法
public static void deserialize() throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user")); User user = (User) ois.readObject(); System.out.println(user.getUserName()); }
- 测试
public static void main(String[] args) throws IOException, ClassNotFoundException { serialize(); deserialize(); }
如果同一个文件再序列化一次的话,文件的大小是不会翻倍,只会在文件写入Header的信息。