How to specify the relative path to the file in the Java file so that it continues to work after the file is placed in the jar file?

Suppose I have a Java class that needs to access a file with the absolute path /home/gem/projects/bar/resources/test.csv:

package com.example class Foo { String filePath = ????? // path to test.csv String lines = FileInputStream(new File(filePath).readAllLines(); } 

If the path to Foo.java is / home / gem / projects / bar / src / com / example.

Of course, I cannot specify the absolute path to the resource file. This is because the jar file will be distributed as a library for any clients that will be used in their own environments.

Assume that a resource file, such as test.csv, is always in the same path relative to the project root. When a jar containing Foo.class is created, this gang also contains test.csv in the same relative path (relative to the project root).

What is the way to specify a relative path that will work no matter where the project pane moves? Also how can I create a jar file (which can be anywhere), so the path to the test.csv resource file will still be correct.

To keep things simple, I used the wrong Java API (readAllLines (), which reads all lines and returns a line containing all the contents of the file. Also do not use try / catch).

Suppose a csv file can be read as well as written to.

Hopefully this will become clear now.

+4
source share
3 answers

Put the test.csv file in the src folder and use this:

 Foo.class.getResourceAsStream("/test.csv") 

Get the InputStream for the file. This will work wherever the project moves, including as a JAR file.

+4
source

Example:

ProjectX \ SRC \ Test.java

ProjectX \ resources \ config.properties

If you have the above structure and want to use the config.properties file, here is how you do it:

InputStream input = new FileInputStream ("./resources/config.projects");

In this example, you donโ€™t have to worry about packing the source in a jar file. You can still change the resource folder at any time.

+2
source

Use getResource() as shown here .

+1
source

All Articles