【Unity实践笔记】根据json文件记录的日期删除过期文件

本文接上

需求分析

所有文件的保存期限为1年,每次启动程序都会进行一次检测,自动删除过期的文件
由于文件保存的时候是以天为文件夹进行集中保存,因此只要整个删掉当日的文件夹即可

文件夹删除后,还需要对引用该文件夹和其中的文件的数据进行处理

使用之前创建的类在这里插入图片描述
其中FDDInfoList和FileDataDaily会作为文件保存,内容分别为FDDInfo和FileDataList序列化的链表

总体步骤如下:

  1. 遍历FDDInfoList.infoList中的FDDInfo文件信息,找到过期的FDDInfo文件及其地址path
  2. 删除存储当天文件的文件夹
  3. 通过path删除该过期FDDInfo文件
  4. 删除FDDInfoList中该过期FDDInfo的信息

因为信息写入的时候是按照时间顺序,因此只要找到距离当前刚好一年的日期就可以停止遍历
由于无法对txt文件中的某一行进行删除操作,所以需要对齐进行重写:

  1. 读取FDDInfoList文件并反序列化获得FDDInfo链表infoList
  2. 遍历infoList,删除过期文件夹和文件
  3. 移除infoList中的该FDDInfo文件的信息
  4. 结束遍历后,将修改后的FDDInfo链表infoList序列化覆盖写入FDDInfoList文件

代码摘录和笔记

 
准备工作

JsonTool jsonTool= JsonTool.Instance;

int year = DateTime.Now.Year;
int month = DateTime.Now.Month;
int day = DateTime.Now.Day;

string json = jsonTool.Read(jsonPathListPath, 1);
JsonPathInfoList jsonPathInfoList = jsonTool.ToClass<JsonPathInfoList>(json);
JsonPathInfo jsonPathInfo = new JsonPathInfo();

 
是否过期的判断

 while(jsonPathInfoList.pathList.Count > 0)
 {
    
    
      jsonPathInfo = jsonPathInfoList.pathList[0];
      if (jsonPathInfo.year == year) break;
      if (jsonPathInfo.month > month) break;

      if (jsonPathInfo.month < month)
      {
    
    
          // 删除指向的文件夹
          Directory.Delete(imgFolderPath + "/" + jsonPathInfo.year + "/" + ToStringWith0(jsonPathInfo.month) + "/" + ToStringWith0(jsonPathInfo.day), true);
          // 删除指向的json文件
          File.Delete(jsonPathInfo.path);
          // 删除链表里的json数据
          jsonPathInfoList.pathList.RemoveAt(0);

          // 删除该月份的空文件夹
          Directory.Delete(imgFolderPath + "/" + jsonPathInfo.year + "/" + ToStringWith0(jsonPathInfo.month));
      }
      else
      {
    
    
          if (jsonPathInfo.day <= day)
          {
    
    
              Directory.Delete(imgFolderPath + "/" + jsonPathInfo.year + "/" + ToStringWith0(jsonPathInfo.month) + "/" + ToStringWith0(jsonPathInfo.day), true);
              File.Delete(jsonPathInfo.path);

              jsonPathInfoList.pathList.RemoveAt(0);
          }
          else break;
      }
  }

 
重写jsonPahtLis

  File.Delete(jsonPathListPath);
  json = jsonTool.ToJson(jsonPathInfoList);
  json = json.Substring(13, json.Length - 15);
  jsonTool.Write(json, jsonPathListPath, out bool a);

这里因为直接序列化了FDDInfoList(一个完整的链表),在读取的时候再次为它添加头和尾会产生重复,无法识别

因此需要使用Substring()对它进行掐头去尾的操作

结束前的吐槽

这个代码是几天前写的,因为是最初几次接触txt和json读取写入,觉得还是有必要记下来
但是现在看来这个代码里有很多可以完善的地方,有些地方的操作有些绕了,有空修改一下

猜你喜欢

转载自blog.csdn.net/weixin_44045614/article/details/109638302