permaculture playing cards*
The moose likes Java in General and the fly likes loading a properties file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "loading a properties file" Watch "loading a properties file" New topic
Author

loading a properties file

vinitha simon
Ranch Hand

Joined: Dec 13, 2007
Posts: 64
I have a properties file in the same folder as my java class. I have tried the following code to load it, but it fails. I get an uncaught NullPointer Exception.

main.java
--------------------------------------------------------------------------------------------------
Properties properties = new Properties();
InputStream stream = null;
try {
stream = getClass().getResourceAsStream("/test.properties");
properties.load(stream);
} catch (IOException e) {
}

and my test.properties file is as follows
---------------------------------------------------------------------------------------------------
subject=Test Mail
body=Dear ${0}:\n\nThis is a test mail.

and the code using message formatter to substitute the values is as follows :

main.java
--------------------------------------------------------------------------------------------------------
String temp=properties.getProperty("body");
java.text.MessageFormat formatter = new java.text.MessageFormat("");
formatter.applyPattern(temp);

Object[] messageArguments = {"Jim Berkley"};

String output = formatter.format(messageArguments);


for some reason, this does not work.... Any help is appreciated!!

TIA
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3414
    
  12
From Class.getResourceAsStream javadoc
...an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').


As your properties file is in the same directory as your class file, you need it to be prefixed by the modified package name, so you need to remove the '/' at the start


Joanne
 
Don't get me started about those stupid light bulbs.
 
subject: loading a properties file
 
Similar Threads
JDK's Bug?! java.util.Properties don't save comments!
reading from property file
Arguments to Properties File
Reading a properties file
JFileChooser