2

How to read properties file from meta-inf folder in a web application from plain java class.

Thufir
  • 8,216
  • 28
  • 125
  • 273
sahoo1989
  • 21
  • 2
  • 6
  • 2
    Please include the code you have tried. Please also include any errors you get. –  Jul 09 '15 at 11:51

3 Answers3

2

The simplest you can do is :-

InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/your.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
System.out.println(prop.getProperty(YourPropertyHere));

OR

you can try loading your properties using FileInputStream also :-

input = new FileInputStream("META-INF/your.properties");
AnkeyNigam
  • 2,810
  • 4
  • 15
  • 23
1

When reading resources, one should take care of closing them properly.

    InputStream streamOrNull = getClass().getClassLoader().getResourceAsStream(
            "META-INF/your.properties");
    if (streamOrNull == null) {
        // handle no such file
    }
    else {
        try (InputStream stream = streamOrNull) { // close stream eventually
            Properties properties = new Properties();
            properties.load(stream);
            // access properties
        }
    }
Frank Neblung
  • 3,047
  • 17
  • 34
0
package net.bounceme.doge.json;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class PropertiesReader {

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(PropertiesReader.class.getName());

    public Properties tryGetProps(String propertiesFileName) {
        log.fine(propertiesFileName);
        Properties properties = new Properties();
        try {
            properties = getProps(propertiesFileName);
        } catch (IOException ex) {
            Logger.getLogger(PropertiesReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        log.info(properties.toString());
        return properties;
    }

    private Properties getProps(String propertiesFileName) throws IOException {
        log.fine(propertiesFileName);
        Properties properties = new Properties();
        properties.load(PropertiesReader.class.getResourceAsStream("/META-INF/" + propertiesFileName + ".properties"));
        log.fine(properties.toString());
        return properties;
    }
}

this works for me.

Thufir
  • 8,216
  • 28
  • 125
  • 273