【HarmonyOS NEXT】查询缓存用storageStatistics.getCurrentBundleStats()接口,如何实现清除应用缓存

 【关键字】

storageStatistics.getCurrentBundleStats() / 获取应用缓存 / 清除应用缓存 / cacheDir

【问题描述】

通过storageStatistics.getCurrentBundleStats() API获取到了应用的缓存大小,请问哪个API可以实现清除应用缓存呢?

【解决方案】

查询缓存用storageStatistics.getCurrentBundleStats()接口,清除文件缓存,需要调用context的cacheDir获取缓存,然后调用系统文件fs接口,判断是文件或者文件夹,再分别消除缓存。

API参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-storage-statistics-0000001774281442

清理demo:

import fs from ‘@ohos.file.fs’;
let cacheDir = context.cacheDir;
@Entry
@Component
struct Clear_cache {
clearCache() {
// let cacheDir = getContext(this).cacheDir
// fs.rmdirSync(cacheDir)
// console.log(“delete !!!”)

fs.listFile(cacheDir).then((filenames) => {
for (let i = 0;i < filenames.length; i++) {
// let dirPath = cacheDir+filenames[i]
let dirPath = ${cacheDir}/${filenames[i]}
// 判断是否文件夹
let isDirectory
try {
isDirectory = fs.statSync(dirPath).isDirectory()
}
catch (e) {
console.log(e)
}

if (isDirectory) {
fs.rmdirSync(dirPath)
} else {
fs.unlink(dirPath).then(() => {
console.info(“remove file succeed”);
}).catch((err) => {
console.info("remove file failed with error message: " + err.message + ", error code: " + err.code);
});
}
}

})
}
}

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值