31

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?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
delmin
  • 2,330
  • 5
  • 28
  • 54

3 Answers3

70

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'
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • is there also any way to use that path package to get also file type.. let's say if the file is an image, document and so on? I doubt that it is possible but if so I will create another question for it – delmin Jun 13 '20 at 10:21
  • https://stackoverflow.com/questions/62361613/how-to-get-type-of-file – delmin Jun 13 '20 at 15:08
6

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

String getFileExtension(String fileName) {
try {
  return "." + fileName.split('.').last;
 } catch(e){
  return null;
 }
}
Yash
  • 1,787
  • 1
  • 22
  • 23
0

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;
  }
Sartaj
  • 139
  • 5