Java 无法通过测试用例从 src/main/resources 访问文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18875635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't access files from src/main/resources via a test-case
提问by tokhi
I have a file.datin src/main/resources.
我有一个file.dat在src/main/resources。
When I try to test a class which loads this file via a jar file, the test fails because its not able to find the file in the path (I/O Exception). The path which I get via test is:
当我尝试测试通过 jar 文件加载此文件的类时,测试失败,因为它无法在路径 ( I/O Exception) 中找到该文件。我通过测试得到的路径是:
/home/usr/workspace/project/target/test-classes/file.dat
/home/usr/workspace/project/target/test-classes/file.dat
but the file is not exist in target/test-classesany idea?
但该文件不存在target/test-classes任何想法?
采纳答案by Jonas Berlin
Files from src/main/resourceswill be available on the classpath during runtime of the main program, while files both from src/main/resourcesand src/test/resourceswill be available on the classpath during test runs.
从文件src/main/resources将可在主程序运行时类路径,而无论是从文件src/main/resources,并src/test/resources会在试运行期间可在classpath。
One way to retrieve files residing on the classpath is:
检索驻留在类路径上的文件的一种方法是:
Object content = Thread.currentThread().getContextClassLoader().getResource("file.dat").getContent();
.. where the type of contentdepends on the file contents. You can also get the file as an InputStream:
.. 类型content取决于文件内容。您还可以将文件作为 InputStream 获取:
InputStream contentStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.dat");
回答by Georgi Eftimov
If the file is in
如果文件在
src/main/resources/file.dat
src/main/resources/file.dat
You can get the URL to the file :
您可以获取文件的 URL:
getClass().getResource("/file.dat");
getClass().getResource("/file.dat");

