【问题标题】:How to specify file path from Main jar, and not for dependency JAR如何从主 jar 指定文件路径,而不是依赖 JAR
【发布时间】:2017-02-20 08:30:01
【问题描述】:

我有一个包含 3 个模块的 java 项目。

[ ] Utils
   ----->code
   ----->pom.xml
[ ] Module B
   ----->Resources\config.xml
   ----->code
   ----->pom.xml
[ ] Module C
   ----->Resources\config.xml
   ----->code
   ----->pom.xml

utils 模块是 Module A 和 Module B 的依赖项。utils 具有 ModuleB 和 ModuleC 都使用的“ReadConfig”功能。模块 B 和模块 C 在资源文件夹中有不同的配置。

Module B 和 Module C 应该理想地作为具有依赖关系的独立 jar 运行,并从目标目录(jar 所在的同一目录)读取 config.xml。

目前我通过以下方式获取配置文件位置:

public static final String JAR_PATH = Constants.class.getProtectionDomain().getCodeSource().getLocation().getPath();
public static final String CONFIG_PATH = JAR_PATH.substring(0, JAR_PATH.lastIndexOf('/')) + "/config.xml";

此代码在 Utils 模块中。

问题是,在 IntelliJ(和 netbeans)中,当我运行项目时,JAR_PATH 是 Utils 目标目录。我希望它指向模块 A 或模块 B 的目标目录。

我的问题是:

  1. 在这种情况下,最佳做法是什么。其中两个模块使用不同的配置文件。
  2. 如何使 intellij / netbeans 在运行模块时将模块 A / B 作为独立的(带有依赖项的 jar)运行(如果我执行 mvn assembly:single 它会生成一个具有有效依赖项的 jar。我想知道如何从智能)

【问题讨论】:

  • 不清楚您要问什么,也请一次问一个问题,因为这两个似乎没有任何关系。

标签: java maven intellij-idea config jar-with-dependencies


【解决方案1】:

如果您需要从运行 jar 应用程序文件的目录中读取某些文件, 然后只需使用:(它将被解析为相对于您运行应用程序的目录)

File f = new File("someDirInDirWhereMyJarIsRunFrom/myConfig.xml");
FileInputStream fis = new FileInputStream(f);
// read the "fis"

这是假设你的应用文件夹的结构是这样的:

  + YourAppFolder
  |---> yourApp.jar
  |---+ someDirInDirWhereMyJarIsRunFrom
      |--->myConfig.xml

【讨论】:

  • 谢谢!这就是我最终要做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多