stelios
stelios

Reputation: 2845

Java: Access relative path outside ANY module

I have a java project that consists of several modules:

myWebApp
  - conf     //not a java module, just text files
  - ModuleA
      -- src
      -- target
      -- moduleA.iml
      -- pom.xml
  - ModuleB
     ...
  - pom.xml
  - myWebApp.iml
  - myWebApp.env

I want to access myWebApp.env file (which is a java properties file) from a Class (which is obviously under a module's src folder), like:

InputStream is = new FileInputStream(<RelativePathToEnvFile>);

The problem is that relative paths seem to work only for subdirectories under modules' source root, or anywhere inside the classpath using the getResource() trick as mentioned here

On every other language I know I could do something like:

InputStream is = new FileInputStream("../../../../../myWebApp.env");

Isn't this possible in java?

Upvotes: 2

Views: 3977

Answers (1)

Gerald M&#252;cke
Gerald M&#252;cke

Reputation: 11122

Since Java 7 you could do this with NIO Files API (old File API would work as well, but relative path resolution is done nicer with NIO)

File file = Paths.get("../../pom.xml").toFile();

To ensure, the file is correct, you could invoke toRealPath() to resolve the relative path segments

File file = Paths.get("../../pom.xml").toRealPath().toFile();

In case you have a working dir to start from, you could resolve a relative path from that:

File file = Paths.get(".") //the current working dir
                 .resolve("../pom.xml") //navigate to a relative path
                 .toFile(); //convert to old File api

When working with an IDE, you have to ensure, the working dir is correct. It is not necessarily the case that the working dir is the same module dir as the executed class belongs to. The working dir could be that of the project/parent module.

In addition, your code may only work in that particular setup. At least you should consider putting the env file in the resources folder of one of your modules (or have a separate config module) and then resolve the file in the classpath.

Upvotes: 4

Related Questions