8

Anyone please help me on reloading properties file. I have code like this

Properties prop = new Properties();
InputStream trackerFileStream = 
    LoadProperty.class.getClassLoader().getResourceAsStream("sample.properties");
prop.load(trackerFileStream);

After loading the properties file through class loader, I modify the properties file. I am not able to get the latest modifications in the same program execution.

Can anyone please suggest me how to reload the properties file without re-executing the program?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Kiran T
  • 211
  • 2
  • 8
  • 16
  • do you execute the above code, after you altered the properties file? – oers Mar 29 '12 at 11:39
  • Why using properties for something they're not intended for ? If you need some data modified why not using something like pub/sub topic where the modifier publishes the change for any subscriber to the changes. You can also use events. – Ali Ben Zarrouk Jun 03 '19 at 23:39
  • Why do you want to change properties in the classpath and not in a relative(or absolute) location at runtime? – dan1st Nov 02 '19 at 07:37
  • Just create a new `InputStream`, clear the `prop` Object an `load` it again. – dan1st Nov 02 '19 at 07:38
  • Are you overwriting the file, once you reload the properties? If you never re-save them to disk, you'll always get the previous result – Joe Dec 02 '19 at 20:06

2 Answers2

3

If you want to be updated you need to check the resource from tome to time and reload the properties.

It is a problem that you are loading properties from classpath. If you use file system you can check the last modified attribute of file and decide whether to reload it. In java 7 you evern can register listener that will call you back when file is modified. You can't do this when loading resource.

But you can do better. Use configuration package from apache. It already implements reloading logic, so you just can work against "configuration" actually mapped to resource and be sure you always get updated data.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Do you close/flush your streams correctly? Why using classloader to access the file? If the file is an external file you should access it via normal FileInputStream for example

jabal
  • 11,987
  • 12
  • 51
  • 99
  • But in my case i can not specify the exact location of the file. That is why i use class loader – Kiran T Mar 29 '12 at 11:37
  • In production practically your application is packed as a .jar file and it is not possible to modify it runtime. Files need to be both read and modified runtime should be placed to designated absolute or relative paths. – jabal Mar 29 '12 at 11:41
  • Thanks jabal, yes after closing the InputStream it is working file(i.e. Am able to read latest value of properties file). – Kiran T Mar 29 '12 at 11:43