使用时继承Externalizable接口自己实现writeExternal和readExternal序列化方法,使用时在保存对象到文件时先实例化生成对象为对象赋值,然后调用对象的save方法保存进文件中,在需要从文件中加载时先new或者初始化一个对象然后调用load方法将文件中数据缓存在对象中,文件就相当于是一个数据库。加载完之后就可以调用set和get方法处理了 out.writeObject()与in.readObject()使用顺序要一致;
public class SkillMode implements Externalizable {
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(SkillMode.class);
private Map<Integer,Definition> allSkill;
private String version;
private String versionMessage;
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(version);
out.writeObject(versionMessage);
out.writeObject(allSkill);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
version = (String) in.readObject();
versionMessage = (String) in.readObject();
allSkill = (Map<Integer, Definition>) in.readObject();
}
public Map<Integer, DmDialogDefinition> getAllSkill() {
return allSkill;
}
public void setAllSkill(Map<Integer, DmDialogDefinition> allSkill) {
this.allSkill = allSkill;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersionMessage() {
return versionMessage;
}
public void setVersionMessage(String versionMessage) {
this.versionMessage = versionMessage;
}
public void load(File file) throws IOException {
logger.debug("File.load path:{}",file.getAbsolutePath());
ObjectInputStream ios = null;
InputStream in = null;
try {
in = new FileInputStream(file);
ios = new ObjectInputStream(new BufferedInputStream(in));
in = null;
this.readExternal(ios);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e);
} finally {
saveClose(ios);
saveClose(in);
}
}
public void save(File file) throws IOException {
ObjectOutputStream oos = null;
OutputStream out = null;
try {
out = new FileOutputStream(file);
oos = new ObjectOutputStream(new BufferedOutputStream(out));
out = null;
this.writeExternal(oos); // 保存对象到文件
} finally {
saveClose(oos);
saveClose(out);
}
}
private void saveClose(AutoCloseable c){
if (c != null){
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}