怎么获取应用已使用的缓存大小，如何使用API清理缓存
==========================

**解决措施**

获取应用已使用缓存大小可以通过[storageStatistics.getCurrentBundleStats](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-storage-statistics#storagestatisticsgetcurrentbundlestats9)来获取。清理缓存需要调用context的cacheDir获取缓存，然后调用系统[@ohos.file.fs](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs) 接口，判断是文件或者文件夹，再分别删除缓存。

如果需要删除整个应用的缓存，必须使用以下代码对所有模块级和应用级的Context进行操作。

**参考代码**

import { fileIo, storageStatistics } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct ClearCache {
 _ // Create a file in the cache_
  writeFile() {
    let filePath = this.getUIContext().getHostContext()!.cacheDir + '/test.txt';
    let fileStream = fileIo.createStreamSync(filePath, 'w+');
    fileStream.writeSync('1145141919810');
    fileStream.close();
  }

 _ // Obtain the size of the application data space_
  getCache() {
    storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => {
      if (error) {
        console.error('getCurrentBundleStats failed with error:' + JSON.stringify(error));
      } else {
        console.info('getCurrentBundleStats successfully:' + JSON.stringify(bundleStats));
        console.info('appsize :' + bundleStats.appSize);
        console.info('cacheSize :' + bundleStats.cacheSize);
        console.info('dataSize :' + bundleStats.dataSize);
      }
    });
  }

 _ // Clear cache_
  clearCache() {
    let cacheDir = this.getUIContext().getHostContext()!.cacheDir;
    console.info(cacheDir);

    fileIo.listFile(cacheDir).then((filenames) => {
      for (let i = 0; i < filenames.length; i++) {
        let dirPath = cacheDir + '/' + filenames\[i\];
        console.log(dirPath);
     _   // Determine whether it is a folder_
        let isDirectory: boolean = false;
        try {
          isDirectory = fileIo.statSync(dirPath).isDirectory();
        } catch (e) {
          console.error(JSON.stringify(e));
        }

        if (isDirectory) {
          fileIo.rmdirSync(dirPath);
        } else {
          fileIo.unlink(dirPath).then(() => {
            console.info('remove file succeed');
          }).catch((err: Error) => {
            console.error('remove file failed with error message: ' + err.message);
          });
        }
      }

    })
  }

  build() {
    Column() {
      Button('Write data to cache')
        .onClick(() => {
          this.writeFile();
        })
      Button('Get the system cache size')
        .onClick(() => {
          this.getCache();
        })
      Button('Click to clear cache')
        .onClick(() => {
          this.clearCache();
        })
    }
  }
}