Relative path for library exporting in Java

Viewed 331

I'm trying to export a .JAR to be used as library to other projects. The problem is that I need to use relative paths when referencing files inside this library, but the only solutions I found were using absolute paths like:

private static final String FILE = new File("").getAbsolutePath().concat("/src/bla/file.txt");

Obviously whenever I try to run this line of code as an exported library I'll get something like DRIVE/project/src/bla/file.txt which is not correct since this .JAR can be anywhere inside DRIVE/projects like DRIVE/projects/lib/myLib.jar.

In Nodejs we had easy functions to retrieve relative paths according to the runtime location. How can I reference files in such a way that it will capture the "runtime path" so that I can safely reference them and the path will be dynamically solved?

For those who are so eager to mark this question as duplicate, please read with attention first. I'm NOT asking how to READ files from resources!

1 Answers

To use the "file.txt" present in the classpath,we need to make sure the "file.txt" is present in the directory represented by classpath.

Assume you have all the class files generated in a directory named "/home/abcuser/target".

For simplicity we will place the file.txt in the target directory root level.

The main class is say TestFileAccess.class(the class with the main method)

To execute the main class present in the target directory you can use the below command

    java -cp /home/abcuser/target TestFileAccess

Now, the classpath in this case is /home/abcuser/target

To access the resources on classpath,you can go with two ways.

  • ClassLoader.getSystemResource and ClassLoader.getSystemResourceAsStream methods.
  • Class.getResource and Class.getResourceAsStream

The main difference between the ClassLoader and Class versions of the methods is in the way that relative paths are interpreted.

The Class methods resolve a relative path in the "directory" that corresponds to the classes package. The ClassLoader methods treat relative paths as if they were absolute; i.e. the resolve them in the "root directory" of the classpath

Using ClassLoader you can use the below snippet

    InputStream inputStream = ClassLoader.getSystemResourceAsStream("file.txt");

To explicitly reference a resource as a classpath file you can add the resource path to the classpath while executing the java code.
Let's say your resource "file.txt" is in /home/abcuser/resources.
You can add the the resource path to the classpath during the java execution start as shown below

    java -cp "/home/abcuser/target:/home/abcuser/resources" TestFileAccess
Related