简体   繁体   English

如何访问主文件和测试文件中的资源

[英]How to access Resources in main and test files

How to access resources(image/file) from main and test classes. 如何从主类和测试类访问资源(图像/文件)。 If I directly give file name where will the resources be looked first for main classes and test classes. 如果我直接给出文件名,那么将在哪里首先查找主要类和测试类的资源。

My requirement: I need give a file in control folder as input to execute the jar file. 我的要求:我需要在控制文件夹中提供一个文件作为执行jar文件的输入。 And control file has file names(to access file in certificates folder) which I should access in my program. 控制文件具有文件名(用于访问证书文件夹中的文件),我应该在程序中访问该文件名。

How to give the file names in above scenarios. 在上述情况下如何给文件名。

Project structure is as follows Project Structure 项目结构如下项目结构

If it is a image: 如果是图像:

String path = "nameOfProject/resources/whateverfolder/imagename.png";
ImageIcon icon= new ImageIcon(getClass().getClassLoader().getResource(path));

It is donot matter which class you are in, if you pass whole path rather than file name. 如果您传递整个路径而不是文件名,那么您属于哪个类都没有关系。

To access a file: 要访问文件:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.txt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法通过测试用例访问src / main / resources中的文件 - Can't access files from src/main/resources via a test-case 如何在test和main之间共享资源? - How to share resources between test and main? 如何访问Maven依赖库的main /资源? - how to access main/resources of a maven dependency lib? 如何访问存储在 Docker 容器中 'src/main/resources/someFolder' 中的应用程序资源文件? - How to access app resource files stored in 'src/main/resources/someFolder' within a Docker container? 当项目为 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 Mule - 在Studio和Standalone中运行时如何访问Java类中src / main / resources中的文件? - Mule - how to access files in src/main/resources in Java class when running in Studio and Standalone? 应用程序(src / main)运行时,类路径中的src / test / resources中的文件是? - Are files in src/test/resources on classpath while application (src/main) is running? 从Java中的src / main / resources访问静态文件 - Access static files from src/main/resources in Java Scalatest 使用主要资源,而不是测试资源 - Scalatest using main resources, not test resources 如何从src / main / java中的src / test / resources中读取道具 - How to read props from src/test/resources in src/main/java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM