String contextPath = request.getServletContext().getRealPath("/");
/**
* 实时获取配置文件
* @param request TODO
*/
public static String getConfigJsHash(HttpServletRequest request){
String contextPath = request.getServletContext().getRealPath("/");
File filename = new File(contextPath+"/static/config_js.txt");
InputStreamReader reader = null;
BufferedReader br = null;
try {
reader = new InputStreamReader(new FileInputStream(filename));
br = new BufferedReader(reader);
String str = br.readLine();
br.close();
reader.close();
LOG.info("config_js hash is "+str);
return str;
} catch (Exception e) {
e.printStackTrace();
} finally {
filename = null;
br = null;
reader = null;
}
return null;
}
/**
* 实时获取配置文件
*/
public static Map<String,Object> getConfigCssHash(String key){
try {
URL fileUrl = Thread.currentThread().getContextClassLoader().getResource("config_css.properties");
Properties prop = new Properties();
prop.load(fileUrl.openStream());
String value = (String) prop.get(key);
LOG.info("cssHash is "+value);
Map<String,Object> cssHashMap = JsonUtils.fromJson(value, Map.class);
return cssHashMap;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
return Maps.newHashMap();
}
private static Properties props = null;
private static Properties CssProps = null;
private static Properties JsProps = null;
static {
try {
props = PropertiesLoaderUtils.loadAllProperties("application.properties");
CssProps = PropertiesLoaderUtils.loadAllProperties("config_css.properties");
JsProps = PropertiesLoaderUtils.loadAllProperties("config_js.properties");
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
public static String getCssProperty(String key) {
return CssProps.getProperty(key);
}
public static String getJsProperty(String key) {
return JsProps.getProperty(key);
}
本文介绍了一种从不同路径加载配置文件的方法,并展示了如何通过Java代码读取这些配置文件的内容。包括了使用HttpServletRequest来获取web应用的真实路径并读取特定目录下的配置文件,以及通过类加载器来获取资源文件。

1万+

被折叠的 条评论
为什么被折叠?



