单个文件夹空间的统计

单个文件夹空间的统计

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%') 
  } 
}
分享
微博
QQ
微信
回复
2024-05-22 15:41:54
相关问题
如何打开指定文件夹,选择文件返回
7301浏览 • 1回复 待解决
apache下文件夹没有访问权限
917浏览 • 0回复 待解决
fs.unlink接口无法删除文件夹
447浏览 • 1回复 待解决
有谁知道如何获取文件夹大小
315浏览 • 1回复 待解决
怎样在根目录中创建文件夹
2687浏览 • 1回复 待解决
是否有将文件夹压缩打包成zipAPI?
291浏览 • 1回复 待解决
分享沙箱文件,应用可分享单个文件
453浏览 • 1回复 待解决
鸿蒙相册里最近删除文件夹在哪?
15719浏览 • 1回复 待解决