In Dart, if I know the root directory and the relative path of a file, how to create a file instance for it?
Directory root = new Directory("/root");
String relativePath = "logs/users.log";
How to create a file instance for the users.log
?
In java, it's very simple:
new File(root, relativePath);
But in Dart, I can't find a simple solution as that.
This is the simplest solution I found
import 'package:path/path.dart' as path;
...
String filePath = path.join(root.path, relativePath);
filePath = path.normalize(filePath);
File f = new File(filePath);
/home/name/
and ../name2
to yield /home/name2
Thank you Günter Zöchbauer for the tip.
It seems linux boxes can handle a path like /home/name/../name2
.
On a windows machine, Path.normalize
needs to be used and the extra /
Path.normalize
preppends at the head must be removed.
Or use new Path.Context():
import 'package:path/path.dart' as Path;
import 'dart:io' show Platform,Directory;
to_abs_path(path,[base_dir = null]){
Path.Context context;
if(Platform.isWindows){
context = new Path.Context(style:Path.Style.windows);
}else{
context = new Path.Context(style:Path.Style.posix);
}
base_dir ??= Path.dirname(Platform.script.toFilePath());
path = context.join( base_dir,path);
return context.normalize(path);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With