1

I am reading properties file by a path like this:

String filePath = "src/main/resources/database.properties";

After I build the jar, the jar tries to again find properties file at this particular path, but fails. Is there a way to pack properties files inside the jar or have a neutral path (path which applies both ways with or without building jar) or any other solution to this?

9gagger07
  • 11
  • 2
  • Possibly related: [Loading resources like images while running project distributed as JAR archive](https://stackoverflow.com/q/9864267) – Pshemo Jan 11 '22 at 10:06
  • The other question specifically involves images. – TheKodeToad Jan 11 '22 at 10:10
  • 1
    Does this answer your question? [How to read from properties file?](https://stackoverflow.com/questions/18239902/how-to-read-from-properties-file) – jhamon Jan 11 '22 at 10:13

1 Answers1

0

Files in "src/main/resources" automatically get bundled into the jar file, meaning that they can be used at runtime no matter where they are run.

If you want to access files inside the JAR, you can use methods provided by Java:

// Get the resource "test.properties" inside the current package.
getClass().getResource("test.properties");
// Get the resource "test.properties" inside "src/main/resources". 
getClass().getResource("/test.properties");

If you want an input stream, you can use getResourceAsStream:

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

You can combine this with a Properties object to read the resource as a properties file:

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

Properties testProperties = new Properties();
testProperties.load(propertiesInput);

propertiesInput.close();
TheKodeToad
  • 301
  • 2
  • 10