getBaseName static method
This method gets the file base name from a path.
getBaseName("/path/to/file/my_file.jpg") == "my_file"
getBaseName("/path/to/file/my_file") == null
getBaseName("/path/to/file/.jpg") == null
Returns null
if filePath
is not formatted in a valid way.
Hint:
filePath
must include a file extension.- If the path contains separators, there must be characters between the last separator and the dot in the file extension.
Note: This method will not work on hidden files. It will view them as a file extension since hidden files like ".gitconfig" look like file extensions to this program and not valid file names.
Implementation
static String? getBaseName(String filePath) {
// Check for empty string.
if (filePath.isEmpty) {
return null;
}
String? fileExt = tryParseFileExt(filePath);
// Check for a valid file extension.
if (fileExt == null || !_isValidFileExt(fileExt)) {
return null;
}
String fileName;
if (filePath.contains(Platform.pathSeparator)) {
fileName = filePath.substring(
filePath.lastIndexOf(Platform.pathSeparator) + 1,
filePath.lastIndexOf("."));
} else {
fileName = filePath.substring(0, filePath.lastIndexOf("."));
}
if (fileName.isEmpty || fileName == Platform.pathSeparator) {
return null;
}
return fileName;
}