Created
August 16, 2022 19:09
-
-
Save Frankdroid7/80e35c3390be3e1e68e6d1803edbd6d5 to your computer and use it in GitHub Desktop.
A simple function to check through a folder in the device if a file name already exists. If it does, append "(1)" to it to make it unique.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This function helps to add a string at the back of each file name IF that | |
// file already exists in the user's file system, so that each file name will | |
// be unique. | |
Future<String> makeFileName(String path, String fileName) async { | |
bool fileExists = await File('$path/$fileName').exists(); | |
if (fileExists) { | |
int counter = 1; | |
List newFileExt = fileName.split('.'); | |
String ext = newFileExt[1]; // refers to the file extension. | |
String fName = newFileExt[0]; | |
String newFileName = '$fName($counter).$ext'; | |
bool newFileExists = await File('$path/$newFileName').exists(); | |
while (newFileExists) { | |
List newFileExt = fileName.split('.'); | |
String ext = newFileExt[1]; | |
String fName = newFileExt[0]; | |
/// The regex here is used to get the last occurrence of something like this: (1) | |
/// (opening and closing bracket with digit(s) inside). The reason for this is that | |
/// it may happen that a file name itself contains (something like this) "(1)" | |
RegExp regExp = RegExp(r'\([0-9]+\)$'); | |
String? stringMatch = regExp.stringMatch(fName); | |
if (stringMatch != null) { | |
fName = fName.replaceAll(regExp, "(${counter + 1})"); | |
} else { | |
fName = "$fName($counter)"; | |
} | |
newFileName = '$fName.$ext'; | |
newFileExists = await File('$path/$newFileName').exists(); | |
counter += 1; | |
} | |
return newFileName; | |
} | |
return fileName; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment