参考如下代码:import common from '@ohos.app.ability.common'; import storageStatistics from "@ohos.file.storageStatistics"; import { BusinessError } from '@ohos.base'; import fs from '@ohos.file.fs'; @Entry @Component struct Page_Context { private context = getContext(this) as common.UIAbilityContext; build() { Column() { Image("xxx").width("100vp").height("100vp") Image("xxx").width("100vp").height("100vp") Image("xxx").width("100vp").height("100vp") Image("xxx").width("100vp").height("100vp") Button("获取上下文目录") .onClick(() => { // 获取应用文件路径 console.info("cacheDir:", this.context.cacheDir); }) Button("获取当前应用的存储空间大小") .onClick(() => { storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => { if (err) { console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`); } else { console.info(`Invoke getCurrentBundleStats succeeded, appsize is ${bundleStats.appSize} Byte`); console.info(`Invoke getCurrentBundleStats succeeded, cacheSize is ${bundleStats.cacheSize} Byte`); console.info(`Invoke getCurrentBundleStats succeeded, dataSize is ${bundleStats.dataSize} Byte`); } }); }) } } } Button("清除缓存") .onClick(()=>{ let cacheDir = this.context.cacheDir; console.info("cacheDir:", cacheDir); fs.listFile(cacheDir).then((filenames: Array<string>) => { console.info("listFile succeed"); for (let i = 0; i < filenames.length; i++) { console.info("fileName: %s", filenames[i]); fs.unlink(`${cacheDir}/${filenames[i]}`) } }).catch((err: BusinessError) => { console.error("list file failed with error message: " + err.message + ", error code: " + err.code); }); })
参考如下代码: