Mayvas
Mayvas

Reputation: 789

Flutter / Dart. How to delete all files but leave 10 latest

How to delete all files in the temp device directory but leave 10 latest with mime type 'audio/mpeg'.

Thanks

Upvotes: 0

Views: 303

Answers (1)

Herry
Herry

Reputation: 199

Iterate through the folder, read the mime type and leave at least 10 files there?

The MIME type can be retrieved as shown in this answer.

Now all that's left is to iterate through the files, where the MIME-type is the desired one, and delete all but 10.

Directory dirToPrune = ...;
List<File> result = [];

for(FileSystemEntity entity in dirToPrune.listSync())
  if(entity is File && lookupMimeType(entity.path)=="audio/mpeg")
    result.add(entity);

while(result.length > 10) {
  File toDelete = result[0];
  result.removeAt(0);
  toDelete.delete();
}

I did not test the code but the idea should be clear.

Upvotes: 2

Related Questions