问题
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