Search code examples
javamavenintellij-ideaconfigjar-with-dependencies

How to specify file path from Main jar, and not for dependency JAR


I have a java project with 3 modules.

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

The utils module is a dependency for both Module A and Module B. The utils have 'ReadConfig' function which both ModuleB and ModuleC uses. Module B and Module C have different configs in the resource folder.

Both Module B and Module C should ideally run as stand-alone jar with dependencies, And read the config.xml from the target directory (the same directory the jar is located in).

Currently i get the config file location through:

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";

This code is in the Utils module.

The thing is, in IntelliJ (and netbeans) when I run the project, the JAR_PATH is the Utils target directory. I want this to point to either Module A or Module B target directory.

My question are:

  1. What is the best practice in this scenario. Where two modules use different config file.
  2. How to make intellij / netbeans run Module A / B as standalone (jar with dependencies) when running the Modules (If i do mvn assembly:single it generates one jar with dependencies that works. I wanna know how to do it from intellij)

Solution

  • If you need to read some file from the directory from where you run your jar app file, then just use: (it will be resolved as relative to the dir from where you run your app)

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

    this is assuming the structure of your app folder is like:

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