How can I get the name of a file in Dart?

2019-06-15 00:49发布

问题:

I found I can't get the name of a file in a simple way :(

Dart code:

File file = new File("/dev/dart/work/hello/app.dart");

How to get the file name app.dart?

I don't find an API for this, so what I do is:

var path = file.path;
var filename = path.split("/").last;

Is there any simpler solution?

回答1:

You can use the path package :

import 'dart:io';
import 'package:path/path.dart';

main() {
  File file = new File("/dev/dart/work/hello/app.dart");
  String filename = basename(file.path);
}


回答2:

Create a new Path object from the file's path, and use its filename property to get the name of the file:

import 'dart:io';

void main() {
  var file = new File('/dev/dart/work/hello/app.dart');
  Path path = new Path(file.path);
  print(path.filename);      // 'app.dart'
  print(path.directoryPath); // '/dev/dart/work/hello'
}


标签: file dart