code: @Transactional(readOnly = true)
    public void cleanupData()
    {
  
      List<String> allFilesInDatabaseList = getJdbcTemplate().queryForList(
        "SELECT filename FROM media_files AS m", String.class);
  
      File dataDir = getRealDataDir();
  
      Set<File> allFilesInDatabase = new HashSet<>();
      for (String singleFileName : allFilesInDatabaseList)
      {
        allFilesInDatabase.add(new File(dataDir, singleFileName));
      }
  
      log.info("Cleaning up the data directory");
      // go through each file of the folder and check if it is not included
      File[] childFiles = dataDir.listFiles();
      if (childFiles != null)
      {
        for (File f : childFiles)
        {
          if (f.isFile() && !allFilesInDatabase.contains(f))
          {
            if (!f.delete())
            {
              log.warn("Could not delete {}", f.getAbsolutePath());
            }
          }
        }
      }
    }
docs: Delete files not used by this instance in the data directory.