在Dart中的库下读取静态文件? [英] Reading static files under a library in Dart?

查看:806
本文介绍了在Dart中的库下读取静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Dart写一个库,我的库文件夹下有静态文件。我想要能够读取这些文件,但我不知道如何检索到它的路径...没有 __ FILE __


$ b 更新:似乎我不够清楚。让我们帮助您理解我:



test.dart

  import'foo.dart'; 

void main(){
print(Foo.getMyPath());
}

foo.dart
$ b

  library asd; 

class Foo {
static Path getMyPath()=>新路径('resources /');
}

它给我错误的文件夹位置。它给了我的路径 test.dart + resources / ,但我想要的路径 foo.dart + resources /

解决方案

如前所述,您可以使用镜像。以下是使用您希望实现的示例:



test.dart



$ b b

  import'foo.dart'; 

void main(){
print(Foo.getMyPath());
}

foo.dart
$ b

  library asd; 

import'dart:mirrors';

class Foo {
static Path getMyPath()=> new Path('$ {currentMirrorSystem()。libraries ['asd']。url} / resources /');
}

它应该输出:


/ Users / Kai / test / lib / resources /


一个更好的方法来做到这一点在未来的版本。



更新:您还可以在库中定义一个私有方法:

  / ** 
*返回此库根目录的路径。
* /
_getRootPath(){
var pathString = new Path(currentMirrorSystem()。libraries ['LIBNAME']。url).directoryPath.toString()。replaceFirst //','');
return pathString;
}


I am writing a library in Dart and I have static files under the library folder. I want to be able to read those files, but I'm not sure how to retrieve the path to it... there is not __FILE__ or $0 like in some other languages.

Update: It seems that I was not clear enough. Let this help you understand me:

test.dart

import 'foo.dart';

void main() {
  print(Foo.getMyPath());
}

foo.dart

library asd;

class Foo {
  static Path getMyPath() => new Path('resources/');
}

It gives me the wrong folder location. It gives me the path to test.dart + resources/, but I want the path to foo.dart + resources/.

解决方案

As mentioned, you can use mirrors. Here's an example using what you wanted to achieve:

test.dart

import 'foo.dart';

void main() {
  print(Foo.getMyPath());
}

foo.dart

library asd;

import 'dart:mirrors';

class Foo {
  static Path getMyPath() => new Path('${currentMirrorSystem().libraries['asd'].url}/resources/');
}

It should output something like:

/Users/Kai/test/lib/resources/

There will probably be a better way to do this in a future release. I will update the answer when this is the case.

Update: You could also define a private method in the library:

/**
 * Returns the path to the root of this library.
 */
_getRootPath() {
  var pathString = new Path(currentMirrorSystem().libraries['LIBNAME'].url).directoryPath.toString().replaceFirst('file:///', '');
  return pathString;
}

这篇关于在Dart中的库下读取静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆