读取classpath下的properties文件并存到字典中
public void contextInitialized(ServletContextEvent servletContextEvent) {
InputStream in = getClass().getClassLoader().getResourceAsStream("/upload.properties");
Properties properties = new Properties();
try {
properties.load(in);
for(Map.Entry<Object,Object > prop: properties.entrySet())
{
String propertyName = (String) prop.getKey();
String propertyValue = (String) prop.getValue();
FileUploadProperties.getInstance().addProperty(propertyName,propertyValue);
}
} catch (IOException e) {
e.printStackTrace();
}
}
其中
getClass().getClassLoader().getResourceAsStream("/upload.properties");
和
getClass().getResourceAsStream("/upload.properties");
的区别如下:
Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致。
例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.class.getResourceAsStream("name")
会在com.test.mycode包下查找相应的资源。
如果这个name是以 '/' 开头的,那么就会从classpath的根路径下开始查找。
ClassLoader.getResourceAsStream() 无论要查找的资源前面是否带'/' 都会从classpath的根路径下查找。