现如今各类信息存储有框架可使用,如logback等日志框架。而通过流保存信息的底层实现较少使用。今天就上手练习了下。
/**
* 对象记录到本地日志文件
* @param Mes
* @return
*/
public static boolean save(Mes Mes){
//导入对象判空
if(Mes==null){
return false;
}
//日志名称如:2021-09-10.txt
String fileName = Mes.getExposureTime() + ".log";
//判断日志文件是否存在,存在打开,不存在新建
File file=new File(dir+fileName);
try {
if(!file.exists()){
file.createNewFile();
}
} catch (IOException e) {
log.info("创建文件失败");
}
//获取日志文件输出流
BufferedWriter out=null;
try {
out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true)));
//格式化对象
String str=convertStr(Mes);
//将格式化对象导入文件
out.write(str);
} catch (Exception e) {
log.info("文件写入失败");
}finally {
try {
out.close();
} catch (IOException e) {
log.info("文件输出流关闭失败");
}
}
return true;
}
/**
* 对象转换为字符串,通过反射获取对象字段信息
* @param Mes
* @return
*/
private static String convertStr(Mes Mes){
StringBuilder str=new StringBuilder();
Field[] fields = Mes.getClass().getDeclaredFields();
try {
for(int i=0;i<fields.length;i++){
fields[i].setAccessible(true);
if(i!=0)str.append('\t');
str.append(fields[i].get(Mes));
}
} catch (IllegalAccessException e) {
log.info("反射获取对象信息失败");
}
str.append("\r\n");
return str.toString();
}