Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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);
}

I found that problem to find relative path of a file inside of my test script file, so I improved the answer of @TastyCatFood to work in that context too. The following script can find the relative of a file every where:

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

///  Find the path to the file given a name
///  [fileName] : file name
///  [baseDir] : optional, base directory to the file, if not informed, get current script path.
String retrieveFilePath(String fileName, [String baseDir]){
  var context;
  // get platform context
  if(Platform.isWindows) {
    context = path.Context(style:path.Style.windows);
  } else {
    context = path.Context(style:path.Style.posix);
  }

  // case baseDir not informed, get current script dir
  baseDir ??= path.dirname(Platform.script.path);
  // join dirPath with fileName
  var filePath = context.join(baseDir, fileName);
  // convert Uri to String to make the string treatment more easy
  filePath = context.fromUri(context.normalize(filePath));
  // remove possibles extra paths generated by testing routines
  filePath = path.fromUri(filePath).split('file:').last;

  return filePath;
}

The following example read the file data.txt in the same folder of main.dart file:

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

main(List<String> arguments) async {
   File f = new File('data.txt');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top