How to get the size of a directory including its files

*爱你&永不变心* 提交于 2021-01-29 11:33:05

问题


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

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?


回答1:


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};
}



回答2:


There is a package named flutter_file_manager. I never used it, but this package has a feature to sort directory according to size. So, i guess you can find the size by using this feature/package.

flutter_file_manager

Make sure you add read/write permission on your AndroidManifest.xml file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


来源:https://stackoverflow.com/questions/57140112/how-to-get-the-size-of-a-directory-including-its-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!