Igor_M
Igor_M

Reputation: 338

Unable to load the configuration application.properties

I'm implementing the piece of code, that make changes in some configuration file. In the very beginning I'm trying to find my application.properties file:

File file = new File(Objects.requireNonNull(this.getClass().getClassLoader().getResource("application.properties")).getFile());

File is located in /opt/pcc/lib/smp-asnef.jar in src/main/resources/application.properties

But I get an error:

Error: Unable to load the configuration from the URL file:/root/file:/opt/pcc/lib/smp-asnef.jar!/BOOT-INF/classes!/application.properties

Can you explain this error (I want to understand where exactly he is looking for a file and what exactly it means)? And what could be a solution?

I'm ready to give additional information if needed.

Upvotes: 2

Views: 2080

Answers (2)

CodeScale
CodeScale

Reputation: 3304

To read a file from a Java jar file uses the getClass and getResourceAsStream methods. Sample :

    InputStream is = getClass().getClassLoader().getResourceAsStream("some_file");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    // some logic
    br.close();
    isr.close();
    is.close();

that make changes in some configuration file.

You can't change any content of a jar which is currently used. Files are considered as "locked". So if you want to modify config I suggest

  • to write this file outside the jar.
  • notify spring by using the spring.config.location cli param
  • choose a way to reload the file on any cnanges - reloading strategy

Upvotes: 0

Tomino
Tomino

Reputation: 475

Resources in the build path are automatically in the classpath of the running Java program. Considering this, you should always load such resources with a class loader. Have a look at this:

String propName = "application.properties"; 
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(propName)) {
    props.load(resourceStream);
}
// use props here ...

Alternatively you could use this getResourceAsStream() method:

import org.apache.commons.io.IOUtils;

String fileName = "application.properties";
ClassLoader classLoader = getClass().getClassLoader();

try (InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
    String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    System.out.println(result);

} catch (IOException e) {
    e.printStackTrace();
}

Let me know if that helped :)

Upvotes: 1

Related Questions