[英]Can't access files from src/main/resources via a test-case
I have a file.dat
in src/main/resources
. 我在
src/main/resources
有一个file.dat
。
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
). 当我尝试通过jar文件测试加载此文件的类时,测试失败,因为它无法在路径中找到该文件(
I/O Exception
)。 The path which I get via test is: 我通过测试获得的路径是:
/home/usr/workspace/project/target/test-classes/file.dat
but the file is not exist in target/test-classes
any idea? 但是
target/test-classes
的文件是不存在的?
Files from src/main/resources
will be available on the classpath during runtime of the main program, while files both from src/main/resources
and src/test/resources
will be available on the classpath during test runs. 在主程序运行期间,
src/main/resources
将在类路径中可用,而来自src/main/resources
和src/test/resources
将在测试运行期间在类路径上可用。
One way to retrieve files residing on the classpath is: 检索驻留在类路径上的文件的一种方法是:
Object content = Thread.currentThread().getContextClassLoader().getResource("file.dat").getContent();
.. where the type of content
depends on the file contents. ..
content
的类型取决于文件内容。 You can also get the file as an InputStream: 您还可以将文件作为InputStream获取:
InputStream contentStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.dat");
If the file is in 如果文件在
src/main/resources/file.dat
SRC /主/资源/ FILE.DAT
You can get the URL to the file : 您可以获取该文件的URL:
getClass().getResource("/file.dat");
。的getClass()的getResource( “/ FILE.DAT”);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.