学习 JavaWeb项目开发案例精粹14(新闻发布系统)之二

这一节写EnvironmentConfig 类,这是一个环境变配置相关的类。

package com.ppcms.common;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Hashtable;

public class EnvironmentConfig {
	public static EnvironmentConfig ec;
	public static Hashtable ht;
	public EnvironmentConfig(){
		
	}
	public static EnvironmentConfig getInstance() {
		if(ec == null){
			ec = new EnvironmentConfig();
		}
		return ec;
	}
	public Properties getProperties(String fileName) {
		Properties p = null;
		InputStream ins = null;
		try{
			p = (Properties)ht.get(fileName);
			if(p == null){
				try{
					ins = new FileInputStream(fileName);
				}catch(Exception e){
					if(fileName.startsWith("/"))
						ins = (com.ppcms.common.EnvironmentConfig.class).getResourceAsStream(fileName);
					else
						ins = (com.ppcms.common.EnvironmentConfig.class).getResourceAsStream("/" + fileName);
				}
				p = new Properties();
				p.load(ins);
				ht.put(fileName, p);
				ins.close();
			}
		}catch(Exception e) {
			e.printStackTrace(System.out);
		}
		return p;
	}
	
	public String getPropertiesValue(String fileName,String strkey) {
		try{
			Properties p = getProperties(fileName);
			return (String)p.get(strkey);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
		return null;
	}

}
主要有三个方法
public static EnvironmentConfig getInstance()   返回一个EnvironmentConfig 实例。

public Properties getProperties(String fileName)   该方法返回一个Properties属性,利用传入参数fileName 返回一个打文件后的属性。
public String getPropertiesValue(String fileName,String strkey)  利用上一方法返回的属性和传来的strkey来取这个的值。


你可能感兴趣的:(学习 JavaWeb项目开发案例精粹14(新闻发布系统)之二)