java对象序列号到磁盘File文件
序列表java对象到磁盘
// 序列化
public static void writeObject(String ai, Object obj) {
File file = new File(MqConstant.MAP_SYS_PARAMS.get(MqConstant.ERROR_DATA_DIR) + "/" + ai);
// 判断文件是否存在
boolean isExist = false;
if (file.exists()) {
isExist = true;
}
FileOutputStream os = null;
ObjectOutputStream oos = null;
try {
os = new FileOutputStream(file, true);
oos = new ObjectOutputStream(os);
// 如果文件存在则截断streamheader;若文件不存在则保留streamheader
if (isExist) {
long pos = os.getChannel().position() - 4;
os.getChannel().truncate(pos);
}
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != oos) {
try {
oos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
反序列化
// 反序列化
public static List readObjects(String ai) {
File file = new File(MqConstant.MAP_SYS_PARAMS.get(MqConstant.ERROR_DATA_DIR) + "/" + ai);
if (!file.exists()) {
return null;
}
List list = new ArrayList();
FileInputStream is = null;
ObjectInputStream ois = null;
try {
is = new FileInputStream(file);
ois = new ObjectInputStream(is);
while (is.available() > 0) {
list.add((ErrorMessage) ois.readObject());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != ois) {
try {
ois.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return list;
}