'How to get the File Extension from a string Path
I've got file path saved in variable and I want to get the file type extension by using path package https://pub.dev/packages/path So far I managed to do it by splitting the string like this
final path = "/some/path/to/file/file.dart";
print(path.split(".").last); //prints dart
Is there any way to achieve this with path package?
Solution 1:[1]
You can use the extension
function in the path
package to get the extension from a file path:
import 'package:path/path.dart' as p;
final path = '/some/path/to/file/file.dart';
final extension = p.extension(path); // '.dart'
If your file has multiple extensions, like file.dart.js
, you can specify the optional level
parameter:
final extension = p.extension('file.dart.js', 2); // '.dart.js'
Solution 2:[2]
No need of any extension. You can try below code snippet.
String getFileExtension(String fileName) {
try {
return "." + fileName.split('.').last;
} catch(e){
return null;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |