Discussions

General J2EE: Load Properties not using fileinputstream

  1. Load Properties not using fileinputstream (2 messages)

    Hi

    I have to load some Properties file.
    Those are packaged in my ear.
    Properties take only fileinputstream to load a file. So I have to keep my properties file out side the ear.
    Can anybody help me, how to load the properties file from packaged ear

    Thanks,
    vivek
  2. Maybe something like this:

    try
    {
    java.net.URL url = this.getClass().getResource("/some-resource.properties");

    java.io.FileInputStream pin = new java.io.FileInputStream(url.getFile());

    java.util.Properties props = new java.util.Properties();

    props.load(pin);
    }
    catch(Exception ex)
    {
    ex.printStackTrace();
    }

    Sincerely,

    Artem D. Yegorov
    http://www.activexml.org
  3. You could also use the java.lang.ClassLoader method getResourceAsStream()...

     ClassLoader cl = this.getClass().getClassLoader();
     InputStream is = cl.getResourceAsStream(<some location>);
     Properties props = new Properties();
     try
     {
        props.load(is);
     }...

    However, the root location for the target properties file will be different depending on what type of container you're executing in when the properties are to be loaded...

    Executing within a Servlet, the Web Module's classloader targets a root location of <content-root> of the WAR file. So the virtual path within the WAR could be "/WEB-INF".

    ...getResourceAsStream("/WEB-INF/propfile.props");

    Executing with an EJB container, the EJB Module's classloader targets that module's virtual root. So you could create a package (e.g. com.serverside.properties) and place your properties file in it, then use...

    ...getResourceAsStream("/com/serverside/properties/propfile.props");

    Property files packaged directly in the EAR (not within a module that the EAR contains) can be loaded using the getBundle() method of java.lang.ResourceBundle. There's a good description of this in the JDK Javadoc.

    Hope this helps!