Hem » Java » Got Java properties

Got Java properties


Some notes on Javaproperties that i gathered from different sources (thanks btw)

Java Properties:

* Properties can be saved to a stream or loaded from a stream.
* Each key and its corresponding value in the property list is a string.
* Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.
* Properties use ISO 8859-1 character encoding. Unicode escapes can be used; however, only a single ‘u’ character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.
* Generally properties should be read by classpath, not by file.

Example of syntax in propertiesfile!

# You are reading the ”.properties” entry.
! The exclamation mark can also mark text as comments.
website = http://www.eff.org
language = English
# The backslash below tells the application to continue reading
# the value onto the next line.
message = Welcome to \
Wikipedia!
# Add spaces to the key
key\ with\ spaces = This is the value that could be looked up with the key ”key with spaces”.
# Unicode
tab : \u0009

How to read properties file in web application?

In a webapplication you don’t wan’t to use the current working directory i.e. /home/Tomcat/bin or something different, but thus not home/Tomcat/webapps/contextname as you would like. (Too see current working directory: System.out.println(new File(”.”).getAbsolutePath()));

However, if still using file-related properties loading use absolute paths. E.g. /full/path/to/file.ext.

Note: Paths in Java
absolute like “/full/path/to/file..xml”;
relative like “path/resource.xml”;

Relative means, relative to the location, where the method was called. The path will be appended if needed.. Absolute will be used as is, only first / will be removed before the search.

In a WAR and etc, The normal practice is to place those kind of resources in the classpath, or to add its full path to the classpath (in an IDE like Eclipse that’s the src folder and the ”build path” respectively). This way you can grab them with help of the ClassLoader by ClassLoader#getResource() or ClassLoader#getResourceAsStream(). It is able to locate files relative to the ”root” of the classpath. In webapplications (or any other application which uses multiple classloaders) it’s recommend to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this, ie ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

This returns the parentmost classloader which has access to all resources. The MyService.class.getClassLoader() will only return the (child) classloader of the class in question which may not per se have access to the desired resource. It will always work in environments with a single classloader, but not always in environments with a complex hierarchy of classloaders like webapps.

MyService.class.getClassLoader().getResourceAsStream(”/p.properties”);
In Thread#getContextClassLoader(), remove the leading /.

getResourceAsStream() will load a file path relative from your application’s classpath.

Another alternative in webapps is the ServletContext#getResource() and its counterpart ServletContext#getResourceAsStream(). It is able to access files located in the public web folder of the webapp project, including the /WEB-INF folder. The ServletContext is available in servlets by the inherited getServletContext() method.

Class.getResourceAsStream() method or the ClassLoader.getResourceAsStream() method?

There are ClassLoader.getResource() and Class.getResource() and they work differently!!!

java docu:

The methods in ClassLoader use the given String as the name of the
resource without applying any absolute/relative transformation (cf. the
methods in Class). The name should not have a leading “/”.

Using getClass().getResourceAsStream(”pos_config.properties”) is dangerous because you’re using a path that’s resolved relative to the given class, and a subclass could change the location against which it’s resolved. Therefore, it’s safest to name an absolute path within the jar:

Foo.class.getResourceAsStream(”/config.properties”)
Foo.class.getClassLoader().getResourceAsStream(”config.properties”)

getResourceAsStream() method or the getResource() method?

getResourceStream uses getResource underneath the hood.

3 Choices:

Put it in the classpath, load it by ClassLoader#getResourceAsStream() with a classpath-relative path:

Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(”filename.properties”));

Here filename.properties is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. Webapp/WEB-INF/lib, Webapp/WEB-INF/classes, Appserver/lib or JRE/lib. If the propertiesfile is webapp-specific, best is to place it in WEB-INF/classes. If you’re developing a project in an IDE, you can also drop it in src folder (the project’s source folder).

Put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader property of Tomcat/conf/catalina.properties.

Put it somewhere in web folder (the project’s web content folder), so that you can load it by ServletContext#getResourceAsStream() with a webcontent-relative path:

Properties properties = new Properties();
properties.load(getServletContext().getResourceAsStream(”/WEB-INF/filename.properties”));

Note that I have demonstrated to place the file in /WEB-INF folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext is in any HttpServlet class just accessible by the inherited GenericServlet#getServletContext().

Put it somewhere in local disk file system so that you can load it the usual java.io way with an absolute local disk file system path:

Properties properties = new Properties();
properties.load(new FileInputStream(”/absolute/path/to/filename.properties”);

I personally prefer putting it in the classpath outside the project (add new path to the classpath), so that I can manage it from outside and so I don’t need to hardcode an absolute disk file system path in my Java code.

How to convert properties file into XML file?

java.util.Properties class come with a storeToXML() method to convert existing properties data into a XML file.

Slashes?

props.setProperty(”test”, ”C:/dev/sdk/test.dat”); Use forward slashes (or \\ or \u005c) even on Windows but rember some occasions on Windows must have backlashes – ie NTLM login where there exists DOMAIN\USERNAME

How to read properties file placed outside war?

Provide the file name using context param or java system parameter.

1.Context Param

daofilename
D:\daofilename.props

2.System Parameter

java -Ddao.filename=D:\daofilename.props server and String propPath = System.getProperty( ”my.app.properties” );

ou should give property file location as java runtime property to your web container..

Such as, java -DmypropertyFile.location=c:/propertyfile.properties -jar yourContainer.jar

If you are using Tomcat you can add any properties you like to the context, look at the documentation for context.xml. All the application servers has their own way of doing this…

Or use JNDI-resources

Apache Commons has a Library Called Apache Commons Configuration , check it out.

Read
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading
http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource
http://www.javaworld.com/javaworld/javaqa/2002-11/02-qa-1122-resources.html
http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html
http://www.eclipsezone.com/eclipse/forums/t101557.html

Advertisements

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut / Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut / Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut / Ändra )

Google+ photo

Du kommenterar med ditt Google+-konto. Logga ut / Ändra )

Ansluter till %s