How to get the File Extension from a string Path

Viewed 19852

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?

3 Answers

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'

No need of any extension. You can try below code snippet.

String getFileExtension(String fileName) {
try {
  return "." + fileName.split('.').last;
 } catch(e){
  return null;
 }
}

This small function can parse filepath or url and find basename, extension and absolute path. It doesn't check file path exist and not check basename is folder or file.

  Map parsePath(String filepath) {
    Map p1 = new Map();
    int ind1 = filepath.indexOf("://");
    if (ind1 > 0) {
      p1["fullpath"] = filepath;
    } else {
      p1["fullpath"] = File(filepath).absolute.path;
    }
    p1["path"] = filepath;
    List<String> v = filepath.split("/");
    if (v.length > 1) {
      p1["basename"] = v.last;
    } else if (filepath.split("\\").length > 1) {
      p1["basename"] = filepath.split("\\").last;
    } else {
      p1["basename"] = v.last;
    }
    p1["extension"] = p1["basename"].split('.').last;
    if (p1["basename"] == p1["extension"]) p1["extension"] = "";
    return p1;
  }
Related