[英]Reading From a File Within Same Directory
我正在使用Groovy Spock框架,IntelliJ和Bazel構建系統編寫測試。 目的是從與測試文件Model3dImporterSpec.groovy
相同目錄中的LamborghiniAventador.obj
讀取測試數據。
我正在獲取java.io.FileNotFoundException
。
def "reading from test file in same directory"() {
given: "some stuff"
//do some stuff here
when: "reading from test file"
def file = Paths.get("LamborghiniAventador.obj").normalize().toFile()
def byteArray = getFileAsByteStream(file.getAbsolutePath())
then: "file should be read and byte array should not be null"
byteArray != null;
}
private static byte[] getFileAsByteStream(String pathToFile) {
return new File(pathToFile).text.getBytes()
}
當我在命令行上搜索時,文件的路徑是: ~/Dev/Master/src/test/java/com/censored/api/editor/model3dparsers/LamborghiniAventador.obj
我可以從桌面上的文件中成功讀取內容,但是一旦在項目空間中重新定位該文件,該文件便會停止工作。
如何從測試文件讀取測試數據,其中測試數據文件和測試文件位於同一目錄中。 在Java(Eclipse)中,這是一項簡單的任務。 我看了很多其他Stackoverflow問題都無濟於事,所以我認為我在這里嚴重缺乏理解。 除了答案外,我還希望解釋。
為澄清而編輯
假設規格Model3dImporterSpec.groovy
位於:
src/test/groovy/org/whatever
LamborghiniAventador.obj
文件應該位於以下位置:
src/test/resources/org/whatever
為什么? 資源文件應與源文件保存在同一目錄下。
然后使用以下命令加載文件:
getClass().classLoader.getResourceAsStream('LamborghiniAventador.obj')
我已經在@Opal的幫助下解決了自己的問題。
1)當您要訪問bazel中的資源時,需要通過添加資源數組來更新構建文件:
resources = ["LamborghiniAventador.obj"],
2) def foo = getClass().getResourceAsStream('LamborghiniAventador.obj')
正如我在更改1)中所做的那樣,@ Opal的建議對我有用。 所以上面的代碼現在是:
def "reading a file in goovy."() {
when: "reading file from same directory"
System.out.println("Going to read from a file in same directory")
def foo = getClass().getResourceAsStream('LamborghiniAventador.obj')
def byteArray = foo.getBytes()
then: "file should be read and byte array should not be null"
byteArray != null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.