如何从普通java类中读取Web应用程序中meta-inf文件夹中的属性文件。
答案 0 :(得分:1)
您最简单的方法是: -
InputStream propertiesIs = this.getClass().getClassLoader().getResourceAsStream("META-INF/your.properties");
Properties prop = new Properties();
prop.load(propertiesIs);
System.out.println(prop.getProperty(YourPropertyHere));
OR
您也可以尝试使用FileInputStream
加载您的媒体资源: -
input = new FileInputStream("META-INF/your.properties");
答案 1 :(得分: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;
}
}
对我而言works。
答案 2 :(得分:0)
阅读资源时,应注意正确关闭资源。
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
}
}