java使用类序列化反序列化(读写文件)
创建类:Role
package com.wbg.springRedis.entity; import java.io.Serializable; public class Role implements Serializable { private int id; private String roleName; private String note; @Override public String toString() { return "Role{" + "id=" + id + ", roleName='" + roleName + '\'' + ", note='" + note + '\'' + '}'; } public Role() { } public Role(String roleName, String note) { this.roleName = roleName; this.note = note; } public Role(int id, String roleName, String note) { this.id = id; this.roleName = roleName; this.note = note; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
一、序列化写文件:
List<Role> list = new ArrayList<>(); for (int i = 0; i < 20; i++) { Role role = new Role(i, "roleName" + i, "note" + i); list.add(role); } FileOutputStream fileInputStream = new FileOutputStream(new File("g:/role.class")); ObjectOutputStream stream = new ObjectOutputStream(fileInputStream); stream.writeObject(list); stream.close();
二、反序列化读取文件:
FileInputStream fileInputStream = new FileInputStream(new File("g:/role.class")); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); System.out.println(objectInputStream.readObject());