如何获取目录的大小,包括其文件 [英] How to get the size of a directory including its files

查看:47
本文介绍了如何获取目录的大小,包括其文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个目录的总大小,包括目录,子文件夹中的文件等等.

I want to get the total size of a directory in flutter, including its files , files in its sub-folders and so on.

我尝试使用 Directory.statSync ,但它似乎只返回目录本身的元大小.

I tried to use Directory.statSync, but it seems to only return the meta size of the directory itself.

我应该递归遍历目录以计算大小吗?如果是这样,是否已经有一个飞镖包(我找不到一个)?

Should I recursively walk the directory to calculate the size? If so, is there a dart package that already does that (I can't find one)?

如果没有,有什么更有效的方法可用?

If not, what more efficient way is available?

推荐答案

这是递归遍历目录(同步版本)的示例.可以使用dir.list()及其listen()方法来完成异步版本.

This is a example walk a directory recursively (sync version). Async version can be done with dir.list() and its listen() method.

Map<String, int> dirStatSync(String dirPath) {
  int fileNum = 0;
  int totalSize = 0;
  var dir = Directory(dirPath);
  try {
    if (dir.existsSync()) {
      dir.listSync(recursive: true, followLinks: false)
        .forEach((FileSystemEntity entity) {
          if (entity is File) {
            fileNum++;
            totalSize += entity.lengthSync();
          }
        });
    }
  } catch (e) {
    print(e.toString());
  }

  return {'fileNum': fileNum, 'size': totalSize};
}

这篇关于如何获取目录的大小,包括其文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆