How to read properties file from meta-inf folder from a POJO

浪尽此生 提交于 2019-12-14 03:59:37

问题


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


回答1:


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");



回答2:


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.




回答3:


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
        }
    }


来源:https://stackoverflow.com/questions/31316490/how-to-read-properties-file-from-meta-inf-folder-from-a-pojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!