/**
* 将对象保存为文件
*
* @param obj
* @param path
*/
public static void writeObjToFile(Object obj, String path) {
new File(path).getParentFile().mkdirs();
CharArrayWriter out = new CharArrayWriter();
PEMWriter pw = new PEMWriter(out);
FileOutputStream fos = null;
try {
pw.writeObject(obj);
pw.close();
fos = new FileOutputStream(path);
fos.write(out.toString().getBytes());
fos.close();
} catch (Exception e) {
throw new RuntimeException("写入文件失败");
}
}
/**
* 将对象保存为文件
*
* @param object
* @param filePath
*/
public static void writeObjToFileV2(Object object,String path){
FileOutputStream out = null;
try {
File file = new File(path);
if (file.exists()) {
file.delete();
}
file.getParentFile().mkdirs();
file.createNewFile();
out = new FileOutputStream(file);
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(object);
objOut.flush();
objOut.close();
} catch (IOException e) {
throw new RuntimeException("写入文件失败");
}
}
注:path为带文件名的全路径。