Created
May 19, 2022 08:59
-
-
Save ebwood/58467c8bd16159ed63d79d400e28f1e9 to your computer and use it in GitHub Desktop.
Create Unique Fiel in dart
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
import 'dart:io'; | |
import 'package:path/path.dart' as path; | |
class FileUtil { | |
static File getUniqueFile(String folderName, final String? fileName) { | |
int num = 1; | |
String destFileName = | |
fileName ?? '${DateTime.now().millisecondsSinceEpoch}'; | |
String extension = path.extension(destFileName); | |
String baseName = path.basenameWithoutExtension(destFileName); | |
File file = File(folderName + path.separator + destFileName); | |
while (file.existsSync()) { | |
destFileName = '$baseName (${num++})$extension'; | |
file = File(folderName + path.separator + destFileName); | |
} | |
return file; | |
} | |
static Future<File> createUniqueFile( | |
String folderName, final String? name) async { | |
File uniqueFile = FileUtil.getUniqueFile(folderName, name); | |
if (!uniqueFile.existsSync()) { | |
await uniqueFile.create(); | |
} | |
return uniqueFile; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment