Unable to load the configuration application.properties

Viewed 565

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.

2 Answers

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 :)

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
Related