Solved

how to call properties file from utility class

Posted on 2003-12-11
19
3,972 Views
Last Modified: 2013-11-23
Hi all,

I'm trying to load a properties file in a utility class so that I can get it from either servlets or other utility classes. Below is my code I've been trying to do it with, which keeps throwing a NPE error. I've tried placing sql.properties in /WEB-INF and /WEB-INF/classes to no avail.

What I"m trying to achieve is a class that only loads the properties file once and then retains it in memory for quick access from other classes. Any insight/suggestions to my approach is certainly welcome :-)

Thanks in advance,

-Pat

import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

public class MyProperties {

  static Logger logger            = Logger.getLogger(MyProperties.class.getName());
  private static Properties props = null;
  private static InputStream in   = null;
 
  static {
    try {
      in = getClass().getResourceAsStream("/WEB-INF/sql.properties");
      props.load(in);
      logger.info("sql.properties loaded");
    } catch (Exception e) {
      logger.error("Unable to load sql.properties, the error is: " + e);
    } finally {
      try {
        in.close();
      } catch (Exception ignored) {}
    }
  }
 
  public static Properties getProps() {
    return props;
  }
}
0
Comment
Question by:pat5star
  • 6
  • 4
  • 3
  • +3
19 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9924636
> in = getClass().getResourceAsStream("/WEB-INF/sql.properties");

try:
in = getClass().getResourceAsStream("/sql.properties");
0
 
LVL 92

Expert Comment

by:objects
ID: 9924639
with your properties file in:
/WEB-INF/classes
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9924647
You can save the reference in the application context
0
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 86

Expert Comment

by:CEHJ
ID: 9924653
In fact you could probably put it in a servlet class and load it at startup so it's ready immediately for access
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 9925901
Is props initialized?
0
 
LVL 4

Expert Comment

by:tapasvi
ID: 9925926
I would rather suggest that put properties file in a classpath, and access it with

String fileName = obj.getClass().getResource("/sql.properties").getFile();
File file = new File(fileName);

This is package independent so evenif you move your sql.properties file from

some.pkg. folder to some.other.pkg , you dont need to change the code for that. just change the env classpath setting and will work.
0
 
LVL 92

Expert Comment

by:objects
ID: 9925970
> I would rather suggest that put properties file in a classpath, and access it with

Thats what Pat is attempting as I understand it.
And what the suggestion I posted above will achieve.

0
 
LVL 4

Expert Comment

by:tapasvi
ID: 9926014
yep, objects you were right partially..in the sense that code you gave was perfect. but

with your properties file in:
/WEB-INF/classes

this line was not required..only requirement is that file should be in classpath..
somehow i am not comfortable with putting propertis file with .class files...it should be outside of ear file.
0
 
LVL 4

Expert Comment

by:tapasvi
ID: 9926016
>..only requirement is that file should be in classpath..

this line is ambiguous...what I meant was...the directory where .properties file resides should be in the classpath..not the file itself.
0
 
LVL 92

Expert Comment

by:objects
ID: 9926059
> i am not comfortable with putting propertis file with .class files.

but you want them in the classpath :)  whats the difference?

you could put them in:

/WEB-INF/classes/props/sql.properties

And then use:

in = getClass().getResourceAsStream("/props/sql.properties");

For this example another suggestion would be to specify the properties in web.xml, and not worry about an external properties file at all.
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 166 total points
ID: 9926085
If pat5star has posted his/ her entire code above in the question, then props.load(in); should throw a NullPointerException because props is null and not initialized to anything else anywhere.

pat5star, which line is throwing the NPE? Did you print the stack-trace?
0
 
LVL 7

Assisted Solution

by:grim_toaster
grim_toaster earned 166 total points
ID: 9926589
mayankeagle is correct, simply place the line:
props = new Properties();
Before your call to props.load and that should solve your null pointer exception
0
 
LVL 7

Expert Comment

by:grim_toaster
ID: 9926621
There is one other thing though.  How are you getting your code to compile???  As the method call getClass() is not static, you will need an instance of the class in order to use it.
0
 
LVL 92

Accepted Solution

by:
objects earned 168 total points
ID: 9926725
In a static context you can use MyProperties.class instead of getClass().
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 9926729
Very true.... I guess he didn't post the exact code.
0
 
LVL 3

Author Comment

by:pat5star
ID: 9926801
Problem solved, here is the working code now:

import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

public class MyProperties {

  static Logger logger            = Logger.getLogger(MyProperties.class.getName());
  private static Properties props = null;
  private static InputStream in   = null;
 
  static {
    try {
      in = MyProperties.class.getResourceAsStream("/sql.properties");
      props = new Properties();
      props.load(in);
      logger.info("sql.properties loaded");
    } catch (Exception e) {
      logger.error("Unable to load sql.properties, the error is: " + e);
    } finally {
      try {
        in.close();
      } catch (Exception ignored) {}
    }
  }
 
  public static Properties getProps() {
    return props;
  }
}


I really appreciate everyones input on this. I would like to split the points up because it was a combination of  Objects, mayankeagle, and grim_toaster's comments that helped me get this working. Can I even split them up 3 ways or is there a better solution? What would make everyone happy? Because I'm happy that it's working now :-)

CEHJ: I just wanted to mention that I appreciate your suggestion as I know that would work as well. I was going to revert to that if I couldn't get this working but I really prefer this approach as I don't have to bother with load-on-startup in the web.xml and because I plan to add to this class later as well. Thanks :-)

-Pat
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 9926978
You have allocated enough points to this question to split between all the people who have answered on this page. Just click on the Split link and then you can split points between everyone, giving them as much as you want, out of 500.

Mayank.
0
 
LVL 92

Expert Comment

by:objects
ID: 9927061
0
 
LVL 3

Author Comment

by:pat5star
ID: 9927065
Done. Thanks all.

-Pat
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
spring jars download 1 35
Which non-HTML GUI front end to use with Java? 3 24
maven disable workspace resolution 1 20
Delphi Seattle StructureView color 1 14
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question