Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file if I know the root directory and relative path?

Tags:

file

dart

dart-io

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.

like image 758
Freewind Avatar asked Mar 03 '14 14:03

Freewind


2 Answers

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);
like image 193
Günter Zöchbauer Avatar answered Oct 20 '22 04:10

Günter Zöchbauer


Joining /home/name/ and ../name2 to yield /home/name2

Edit:

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);
}
like image 44
3 revs Avatar answered Oct 20 '22 04:10

3 revs