需求说明
将从数据库查到的数据转换成list形式,序列化为文件,进而实现数据数据备份。恢复时再反序列化为list;
public class DataController {
private FileHelper fileHelper;
public String text() {
ArrayList<Object> list = new ArrayList<>();
HashMap<Object, Object> map1 = new HashMap<>();
map1.put("name","张三");
map1.put("age","24");
map1.put("sex","男");
list.add(map1);
File filepaths= new File("d:/file");
try {
fileHelper.saveObjToFile(filepaths, list ); //序列化文件
return 备份成功;
} catch (Exception e) {
e.printStackTrace();
return "备份失败";
}
}
判断文件夹是否存在并调用读取数据方法
public Object judgeDocuments(String filelPath) throws IOException {
File file = new File(filelPath);
JsonResult jsonResult = new JsonResult();
File[] filess = file.listFiles();
try {
if (file.exists()) {
if (filess.length == 0) {
jsonResult.setMessage(“文件夹是空的”);
} else {
for (File files1 : filess) {
if (files1.isDirectory()) {
judgeDocuments(files1.getAbsolutePath());
recoveryFile(files1.getAbsolutePath());
} else {
FileHelper.getObjFromFile(files1.getAbsolutePath());
recoveryFile(files1.getAbsolutePath());
}
}
jsonResult.setSuccess(true);
jsonResult.setMessage(“恢复成功”);
}
} else {
jsonResult.setMessage(“文件不存在”);
}
jsonResult.setSuccess(false);
} catch (Exception e) {
e.printStackTrace();
jsonResult.setError(e.getMessage());
jsonResult.setMessage(“恢复失败”);
}
return jsonResult;
}
读取数据
public void recoveryFile(){
List objFromFile = FileHelper.getObjFromFile(file);
System.out.println(objFromFile);
}
}
public class FileHelper {
序列化保存数据
public String saveObjToFile(String filepaths, List list) {
SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMMddHHmmss”);
String filename = null;
try {
filename = filepaths + “.dat”;//定义文件名称
File files = new File(filepaths);
File file = new File(filename);
if (!files.exists()) {//查看文件夹是否存在没有则创建
files.mkdirs();
}
if (!file.exists()) {//查看文件是否存在
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//写对象流的对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(list); //将Person对象p写入到oos中
oos.close(); //关闭文件流
return filename;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
序列化读取数据
public static List getObjFromFile(String filepath) {
try {
ObjectInputStream stream = new ObjectInputStream(new FileInputStream(filepath));
List lsit = (List) stream.readObject();
return lsit;
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (ClassNotFoundException e) {
}
return null;
}
}