Unable to load .properties in application for Tomcat
package util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
*
* @author proger
*/
public class ProgrammSettings {
private static Logger logger = Logger.getRootLogger();
private static String propertiesPath = "program.settings.properties";
private static Properties props;
public static String getProperty(String key) {
if (props == null)
开发者_运维技巧 loadProperties();
return props.getProperty(key);
}
public static void setResourcesFilePath(String path) {
propertiesPath = path;
}
private static void loadProperties() {
InputStream propOut = null;
try {
//URL url = ClassLoader.getSystemResource(propertiesPath);
propOut = ClassLoader.getSystemClassLoader().getResourceAsStream(propertiesPath); //new FileInputStream(url.getFile());
props = new Properties();
props.load(propOut);
} catch (Exception ex) {
//Logger.getLogger(ProgrammSettings.class.getName()).log(Level.SEVERE, null, ex);
String errorMessage = "Error during properties file reading. Path to file: '" +
propertiesPath + "'";
logger.error(errorMessage, ex);
throw new RuntimeException(errorMessage, ex);
} finally {
try {
if (propOut != null)
propOut.close();
} catch (IOException ex) {
logger.error("Error during closing stream from properties file", ex);
}
}
}
}
I wanted the same code worked both for tests and app classes, so I read properties file from classPath. All my tests pass and my .properties file is packed into war by Maven. But when I run my App from Netbeans this I receive:
java.lang.NullPointerException
java.util.Properties$LineReader.readLine(Properties.java:435)
java.util.Properties.load0(Properties.java:354)
java.util.Properties.load(Properties.java:342)
util.ProgrammSettings.loadProperties(ProgrammSettings.java:49)
util.ProgrammSettings.getProperty(ProgrammSettings.java:33)
dataacess.AbstractDataMapper.loadDriver(AbstractDataMapper.java:58)
dataacess.AbstractDataMapper.<init>(AbstractDataMapper.java:41)
dataacess.UserMapper.<init>(UserMapper.java:25)
servlets.UserRegistration.processRequest(UserRegistration.java:86)
servlets.UserRegistration.doPost(UserRegistration.java:132)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
How can I fix it? Thank you in advance
Place program.settings.properties
in webapps/appname/WEB-INF/classes
And you can use a simpler line ProgrammSettings.class.getResourceAsStream(..)
(i.e. not the system classloader, but the current classloader)
精彩评论