Search code examples
javaproperties-file

Write to Properties File in Java without knowing it's path


I am loading my properties file using the class loader as follows.

Properties prop = new Properties();
prop.load(MyClass.class.getResourseAsStream("/Property.properties"));

Now, using this method I am able to read the properties file. I want to write some data to the property file. I don't know the path of the property file. How do I store the data to the property file then ?

Update

I tried the following, but it doesn't give me the correct path:

File propFile = new File("Property.properties");
System.out.println(propFile.getAbsolutePath());

Solution

  • I don't think you can in a generic way that would always work, because your properties file could be bundled inside a jar, etc. You can get the URL via getResource(String) and then do something with that URL, for example if it's a file URL, you could get the file name there.

     URL u=MyClass.class.getResource("/Property.properties");
     if ("file".equals(u.getProtocol()){
        File f=new File(u.toURI());
     }
    

    But that wouldn't work in all cases.

    I would write the modified value to a file in a well known location, and use the bundled Properties as the default value, that are overriden by the values in the file.