简体   繁体   English

无法通过测试用例访问src / main / resources中的文件

[英]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/resourcessrc/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.

相关问题 从Java中的src / main / resources访问静态文件 - Access static files from src/main/resources in Java Java 无法访问 src/main/resources 中的 txt 文件 - Java can't access txt file in src/main/resources Gradle 无法使用 JavaFX 插件从 src/test 访问模块 src/main 中定义的类 - Gradle can't access classes defined in module src/main from src/test with JavaFX plugin JavaDoc无法从src / main / resources添加自定义样式表 - JavaDoc can't add custom stylesheet from src/main/resources 应用程序(src / main)运行时,类路径中的src / test / resources中的文件是? - Are files in src/test/resources on classpath while application (src/main) is running? 如何从src / main / java中的src / test / resources中读取道具 - How to read props from src/test/resources in src/main/java 无法从控制器中的src/main/webapp/WEB-INF/resources/img访问图像文件以在jsp中显示 - Can't access image file from src/main/webapp/WEB-INF/resources/img in controller to display in jsp Spring启动测试没有从src / main / resources中获取hbm.xml文件 - Spring boot test not picking up hbm.xml files from src/main/resources 当项目为 a.jar 或 IDE 时,如何动态访问 src/main/resources 中的文件 - How can i access files in src/main/resources dynamically when the project is a .jar or in IDE 如何访问主文件和测试文件中的资源 - How to access Resources in main and test files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM