【发布时间】:2021-09-07 02:12:37
【问题描述】:
我一直在寻找实际示例来了解获取资源的 Maven 相对路径最佳实践,但是我很困惑,希望您能支持我了解什么是获取资源的最佳实践以及如何应用于具体例子:
具体例子:
结构 假设我有以下结构并试图从文件夹规划中的一个类中获取一个资源(位于资源中),所以基本上我正在尝试创建一个与 maven 执行一致的相对路径的字符串:
├───.settings
├───images
├───src
│ ├───main
│ │ ├───java
│ │ │ └───com
│ │ │ └───moga
│ │ │ ├───planning --->Trying to get a resource from here
│ │ │ ├───population
│ │ │ │ ├───chromossome
│ │ │ │ ├───gene
│ │ │ │ └───initialpopulation
│ │ │ └───utils
│ │ └───resources
│ │ └───com
│ │ └───moga
│ │ └───planning
│ │ └───sample
│ └───test
│ ├───java
│ │ └───com
│ │ └───moga
│ │ ├───planning
│ │ └───population
│ │ ├───chromossome
│ │ └───gene
│ └───resources
│ └───com
│ └───moga
│ └───planning <-- Resource that I want to get is here
│ └───sample
└───target
├───classes
│ └───com
│ └───moga
│ ├───planning
│ │ └───sample
│ ├───population
│ │ ├───chromossome
│ │ ├───gene
│ │ └───initialpopulation
│ └───utils
├───generated-sources
│ └───annotations
├───generated-test-sources
│ └───test-annotations
├───maven-archiver
├───maven-status
│ └───maven-compiler-plugin
│ ├───compile
│ │ └───default-compile
│ └───testCompile
│ └───default-testCompile
├───surefire-reports
└───test-classes
└───com
└───moga
├───planning
│ └───sample
└───population
├───chromossome
└───gene
获取资源的类 RunCapacityPlanning 我目前正在使用以下快速修复
Path pathCapacityPlanningGeneral = Paths.get(System.getProperty("user.dir"),
"src","test","resources","com","moga","planning","paramsGeneral.txt");
File file = new File(pathCapacityPlanningGeneral.toString());
if (!file.exists()) {
System.out.println("File Do not exist");
System.out.println(pathCapacityPlanningGeneral.toString());
}
以上代码是用mvn包构建的,文件存在(不打印信息)。
POM
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
...
方法 以下是我发现的一些潜在方法:
- Maven Official
File file = new File( path ); if ( !file.isAbsolute() ) { file = new File( project.getBasedir(), file ); }
为了测试这种方法,我尝试了以下方法:
来自this 我知道我应该将此添加到我的 POM 中
<properties>
<project.basedir>somepath</project.basedir>
...
</properties>
- 我应该在这个 somepath 中添加什么? 我已经测试了将 somepath 留空并尝试在我的课堂上打印以理解,但它显示无法解决。
public static void main(String[] args) throws IOException {
// 1) Approach 1
// $ cannot be resolved to a variable,
// project cannot be resolved
System.out.println(${project.baseDir});
- 使用 getResource 基本上我测试了修改主文件:
URL pathCapacityPlanningGeneral =
RunCapacityPlanning.class.getResource("paramsGeneral.txt");
File file = new File(pathCapacityPlanningGeneral.toString());
if (!file.exists()) {
System.out.println("File Do not exist");
System.out.println(pathCapacityPlanningGeneral.toString());
}
以上mvn package java -cp target/CapacityPlan-1.0-SNAPSHOT.jar com.moga.planning.RunCapacityPlanning 后抛出:
File Do not exist
jar:file:/C:/Users/.../capacityplan/target/capacityplan-1.0-SNAPSHOT.jar!/com/moga/planning/paramsGeneral.txt
有人知道我在这种方法中做错了什么吗?
提前非常感谢
【问题讨论】: