1

I needed some configuration file. So I created a config.properties in resources. Is that the best way to do it ? It looks quite heavy. But maybe better than accessing a database.

Properties properties = new Properties();

try 
{
    File file = ResourceUtils.getFile("classpath:config.properties");
    InputStream in = new FileInputStream(file);
    properties.load(in);
    String maxHolidays = (String) properties.get("maxHolidays");
    properties.setProperty("maxHolidays", "20");
}
catch(Exception e)
{
    System.out.println("");
}

if I want to set a new value to my property "maxHolidays" is it also possible from code

Juliette
  • 39
  • 3
  • 1
    Note that your code assumes this is a file on disk. – Thorbjørn Ravn Andersen May 06 '20 at 14:39
  • There are easier ways to get those values, look at e.g. `@Value`. – jonrsharpe May 06 '20 at 14:40
  • I just put the file in resources folder. Should not give error when I let it run in live mode on server – Juliette May 06 '20 at 14:45
  • Does this answer your question? [How to write values in a properties file through java code](https://stackoverflow.com/questions/22370051/how-to-write-values-in-a-properties-file-through-java-code) – David Brossard May 06 '20 at 14:52
  • if I get the file by using getFile("classpath:config.properties") Class path, could that be a problem if I not use an IDE but just pure virtual machine. Do I provide this paramater to vm ? – Juliette May 06 '20 at 15:50

1 Answers1

1

In order to use properties and read values:

@Configuration
@PropertySource("classpath:config.properties")
public class ExampleConfig {

    @Value("${maxHolidays}")
    private String maxHolidays;

    public String getMaxHolidays() {
        return maxHolidays;
    }
}

You then can @Autowire that config into any component, and read the value of maxHolidays.

if I want to set a new value to my property "maxHolidays" is it also possible from code 

If the change is transient, you can add a setter as well.

If you intend to persist the change back to the properties, you can no longer use them as a classpath resource (as this resource usually gets bundled into your JAR), but need file-based properties - in that case, use https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html, which provide load and store methods.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • Where should I put the ExampleConfig class ? Yes I want to persist the value. It should be persisted in the .properties file. Ah ok. If I want to persist it I cannot use the path as I did in my code, but instead have to use src/main/resources/config.properties and not classpath: – Juliette May 06 '20 at 15:05