问题
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