用了一下序列化,留个记录
@GetMapping("/hello")
public String helloworld() {
String filePath = "D:\\objectFile.obj";
try {
File file = new File(filePath);
if (file.exists()) {//先判断文件是否存在,若文件不存在,直接创建ObjectInputStream会报错
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
int c = in.readInt();
System.out.println(c);
Count = ++c;
in.close();
} else {
System.out.println(Count);
}
//若文件不存在,直接创建ObjectOutputStream不会报错,会在指定路径下生成文件
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filePath));
out.writeInt(Count);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return "访问成功";
}
注:若是要序列化对象,对象所在类需实现Serializable接口,若是要忽略对象某个属性,用transient标注