如果我知道根目录和相对路径,如何获取文件?

时间:2014-03-03 14:19:09

标签: file dart dart-io

在Dart中,如果我知道根目录和文件的相对路径,如何为它创建文件实例?

Directory root = new Directory("/root");
String relativePath = "logs/users.log";

如何为users.log创建文件实例?

在java中,它非常简单:

new File(root, relativePath);

但在Dart,我找不到一个简单的解决方案。

3 个答案:

答案 0 :(得分:5)

这是我找到的最简单的解决方案

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

...

String filePath = path.join(root.path, relativePath);
filePath = path.normalize(filePath);
File f = new File(filePath);

答案 1 :(得分:2)

加入/home/name/../name2以获得/home/name2

编辑:

谢谢GünterZöchbauer的提示 似乎linux盒子可以处理像/home/name/../name2这样的路径。

在Windows机器上,需要使用Path.normalize,并且必须删除头部的额外/ Path.normalize

或者使用新的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);
}

答案 2 :(得分:0)

我发现了在测试脚本文件中查找文件的相对路径的问题,因此我改进了@TastyCatFood的答案,使其也可以在这种情况下工作。以下脚本可以在每个位置找到文件的相对位置:

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

以下示例读取与main.dart文件相同的文件夹中的文件 data.txt

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

main(List<String> arguments) async {
   File f = new File('data.txt');
}
相关问题