Thom
Thom

Reputation: 15092

Need location for properties file that can be updated

In my Java EE web application, I need a place to put my properties file where I can find it using getResource() and then update that file.

Placing it in the lib directory doesn't seem to have worked for tomcat. Suggestions?

The application is that GXT needs to have a properties file to hold internationalized strings. I have a requirement to load these strings from a database table. So I have to create the properties file on startup. I am creating an empty one that goes into my jar file in the lib directory. Then I find that file and write to it with the new answers. It all works in jetty, but not in tomcat.

Thanks.

Upvotes: 0

Views: 238

Answers (2)

DejanR
DejanR

Reputation: 461

    //read properties    
    Properties prop = new Properties();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();            
    InputStream stream = loader.getResourceAsStream("sample.properties");
    prop.load(stream);      
    //now save back, take as URL 
    java.net.URL f = loader.getResource("sample.properties");   
    File file = new File(f.getPath());
    OutputStream outstream = new FileOutputStream(file);
    prop.store(outstream, "");
    outstream.close();

But I will suggest using of http://commons.apache.org/configuration/howto_properties.html , because of diferen features including keeping the file "user readable" after store()

Upvotes: 0

BalusC
BalusC

Reputation: 1109625

You can't necessarily reliably write to a classpath location as it might not represent a local disk file system path. You can only write to a (absolute) disk file system location.

Best would be to have a known fixed disk file system location which is in turn also added to the classpath, so that you could use both ClassLoader#getResource() to load it from the classpath and FileOutputStream to write it to the local disk file system.

In case of Tomcat, you can add a fixed disk file system location to the classpath by the shared.loader property of /conf/catalina.properties. E.g.

shared.loader = /var/webapp/conf

It might be useful as well to add a property representing the fixed disk file system location to the properties file itself.

my.location = /var/webapp/conf

This way you can read it as

Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("foo.properties");

And save as

properties.store(new FileOutputStream(new File(properties.getProperty("my.location"), "foo.properties")));

See also:

Upvotes: 3

Related Questions