单个文件夹空间的统计

单个文件夹空间的统计

HarmonyOS
2024-05-20 21:53:49
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

根据官网API说明,@ohos.file.statvfs中的getTotalSize(path: string): Promise接口统计的是文件系统的空间字节数,不适用于单个文件夹空间的统计场景。单个文件夹空间的统计场景推荐使用@ohos.file.fs (文件管理)相关接口。

使用的核心API

@ohos.file.fs

核心代码解释

import fs from '@ohos.file.fs'; 
 
/** 
 * 每个应用的缓存目录: 
 * /data/app/el2/100/base/xxxx应用包名/haps/entry/cache 
 * 
 */ 
@Entry 
@Component 
struct Index { 
  private path: string = ''; 
 
  getCachedTotalSize(pathDir: string, callback: Function) { 
    fs.listFile(pathDir).then((fileNameArray: string[]) => { 
      console.info(`${pathDir} 下包含文件数:${fileNameArray.length}`); 
      let totalSize = 0; 
 
      try { 
        for (let fileName of fileNameArray) { 
          let stat = fs.statSync(pathDir + "/" + fileName) 
          console.info(`${pathDir} file:${fileName}   size:${stat.size}`) 
          totalSize += stat.size; 
        } 
        callback(totalSize); 
      } catch (err) { 
        console.error(`stat error: ${err.message}`); 
        callback(-1); 
      } 
    }) 
  } 
 
  build() { 
    Row() { 
      Column() { 
        Text(this.path) 
          .fontSize(50) 
          .fontWeight(FontWeight.Bold) 
 
        Button('点击统计总字节数') 
          .onClick(() => { 
            this.path = getContext().cacheDir; 
            this.getCachedTotalSize(this.path, (totalSize: number) => { 
              promptAction.showToast({ 
                message: `${this.path} 的总字节数:${totalSize}`, 
                duration: 1000 
              }) 
            }); 
          }); 
 
 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
分享
微博
QQ
微信
回复
2024-05-22 15:41:54
相关问题
打包包含ohosTest文件夹和test文件夹
1614浏览 • 1回复 待解决
如何打开指定文件夹,选择文件返回
9799浏览 • 1回复 待解决
apache下文件夹没有访问权限
3287浏览 • 0回复 待解决
HarmonyOS 获取手机图片文件夹
1161浏览 • 0回复 待解决
HarmonyOS rawFile文件夹合并问题
964浏览 • 1回复 待解决
HarmonyOS 下载文件到指定文件夹
977浏览 • 1回复 待解决
鸿蒙是否有对文件夹加密接口?
1408浏览 • 2回复 待解决
HarmonyOS 图片文件夹获取封面图coverUri
1089浏览 • 1回复 待解决
fs.unlink接口无法删除文件夹
2755浏览 • 1回复 待解决
HarmonyOS 原有Flutter项目增加ohos文件夹
956浏览 • 1回复 待解决
ATS如何判断路径是文件夹还是文件
1359浏览 • 1回复 待解决