2012-09-27 33 views
2

我正在Dart編寫一個庫,我在庫文件夾下有靜態文件。我希望能夠閱讀這些文件,但我不知道如何檢索它的路徑......沒有__FILE__$0像其他一些語言一樣。在Dart的庫中讀取靜態文件?

更新:看來我還不夠清楚。讓這個幫助你理解我:

test.dart

import 'foo.dart'; 

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

foo.dart

library asd; 

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

它給了我錯誤的文件夾位置。它給我的路徑test.dart + resources/,但我想要的路徑爲foo.dart + resources/

回答

4

如上所述,您可以使用鏡像。下面是使用你想達到什麼樣的一個例子:

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

它應該輸出是這樣的:

/Users/Kai/test/lib/resources/

在將來的版本中可能會有更好的方法來做到這一點。在這種情況下,我會更新答案。

更新:你也可以定義庫中的一個私有方法:

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

它實際上在路徑中有文件名,但這是一個小問題。 – Tower

1

通常,通過使用相對路徑來訪問位於庫中靜態位置的資源的常用方法。

#import('dart:io'); 

... 

var filePath = new Path('resources/cool.txt'); 
var file = new File.fromPath(filePath); 

// And if you really wanted, you can then get the full path 
// Note: below is for example only. It is missing various 
// integrity checks like error handling. 
file.fullPath.then((path_str) { 
    print(path_str); 
}); 

查看PathFile

順便說一句..除了API的信息,如果你絕對想獲得相同類型的輸出爲__FILE__你可以做類似如下:

#import('dart:io'); 
... 
var opts = new Options(); 
var path = new Path(opts.script); 
var file = new File.fromPath(path); 
file.fullPath().then((path_str) { 
    print(path_str); 
}); 
+1

你知道,這是行不通的。這就是我最初問這個問題的原因。第一個代碼示例將在最初的腳本所在的位置查找「resources」文件夾,而不是當前正在執行的代碼文件所在的位置。對於第二個代碼示例,同樣的問題是真的,它給了我'test.dart'作爲文件(它應該),而不是'test.dart'中導入的'another.dart'。 – Tower

2

dart鏡像API(仍然是實驗性的,並且不適用於所有平臺,例如dart2js),它暴露了url Getter on LibraryMirror。這應該給你你想要的。

我不知道有任何其他方式可以在圖書館獲取此信息。

#import('dart:mirrors'); 
#import('package:mylib/mylib.dart'); 

main(){ 
    final urlOfLib = currentMirrorSystem().libraries['myLibraryName'].url; 
}