request.getServletContext().getRealPath

本文介绍了一种从不同路径加载配置文件的方法,并展示了如何通过Java代码读取这些配置文件的内容。包括了使用HttpServletRequest来获取web应用的真实路径并读取特定目录下的配置文件,以及通过类加载器来获取资源文件。

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);
	}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值