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

5
  • 1
    Note that your code assumes this is a file on disk. Commented May 6, 2020 at 14:39
  • There are easier ways to get those values, look at e.g. @Value. Commented May 6, 2020 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 Commented May 6, 2020 at 14:45
  • Does this answer your question? How to write values in a properties file through java code Commented May 6, 2020 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 ? Commented May 6, 2020 at 15:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.