Java J2EE读取配置文件

该博客主要介绍了如何在Java J2EE环境中读取配置文件。首先检查环境变量`CONF_HOME`,其次尝试从`web.xml`中获取,最后通过查找`ProtectionDomain/CodeSource/Location/getFile/WEB-INF/conf`目录下的`.properties`文件进行加载。使用并发安全的`ConcurrentHashMap`存储配置信息,并提供静态方法`getProperty`来获取配置项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.InitialContext;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 读取配置文件
 */
public class ReadProperty {

	private static final Logger logger = LoggerFactory.getLogger(Globals.class);
	
	private static String confHome = null;

	//并发,线程安全的map
	private static Map<String, String> confProperties = new ConcurrentHashMap<>();
	private static Map<String, File> confFiles = new ConcurrentHashMap<>();

	//加载成功
	private static boolean loadingSuccess = true;
	

    /**
     * 加载配置文件
	 */
	private synchronized static void loadProperties() {

		//如果没有加载成功,返回
		if ( !loadingSuccess ) {
            return;
		}

		//如果加载的文件是空的
		if (confProperties.isEmpty()) {

			//如果电脑环境变量中为空
			if (confHome == null) {
	        	confHome = System.getProperty("CONF_HOME");
	        }

	        //如果web.xml中没配
	        if (confHome == null) {
	            try {
	                InitialContext context = new InitialContext();
	                confHome = (String)context.lookup("java:comp/env/CONF_HOME");
	            } catch(Exception e) {
	            	logger.warn("Can not find jini name {}", "java:comp/env/CONF_HOME");
	            }
	        }

	        //如果还是为空,就找本机路径下的ProtectionDomain/CodeSource/Location/getFile/WEB-INF/文件夹/conf
	        if (confHome == null) {
	        	confHome = (new InitWebPath()).getRootPath() + "WEB-INF" + File.separator + "conf";
	        }

	        //是否是文件夹
		   try {
			   File dirFile = new File(confHome);
			   if(!dirFile.exists() || (!dirFile.isDirectory())){ 
				   logger.warn("Can not find home or is not directory!\n{}", confHome);
				   loadingSuccess = false;
				   return;
			   }

			   //获取所有文件后缀是.properties的文件名
			   File[] files = dirFile.listFiles(new FileFilter() {
				   @Override
				   public boolean accept(File file) {
					   String fileName = file.getName();
					   int pos = fileName.lastIndexOf(".properties");//最后一个匹配的 db.xml和db.xml.xml
					   
					   if (pos != -1) {  
						   confFiles.put(fileName.substring(0, pos), file);//文件名与文件关联 key value 
						   return true;
					   } else {
						   pos = fileName.lastIndexOf(".xml");
						   confFiles.put(fileName.substring(0, pos), file);
						   return false;
					   }
				   }
			   }
			   );

			   //迭代文件,读取key value
			   for(File file : files) {
				   Properties fileProperties = new Properties();
				   fileProperties.load(new FileReader(file));
				   Iterator<Entry<Object, Object>> iterProp = fileProperties.entrySet().iterator();
				   while(iterProp.hasNext()) {
					   Entry<Object, Object> row = iterProp.next();
					   Object key = row.getKey();
					   Object value = row.getValue();
					   if (null!=key && null!=value) {
						   confProperties.put(key.toString(), value.toString());
					   }
				   }
			   }
		   } catch(Exception e) {
			   loadingSuccess = false;
		   }
		}
	}

	/**
	 * 读取配置文件信息
	 * @param name key
	 * @return value
	 */
	public static String getProperty(String name) {
		if (confProperties.isEmpty()) {
			loadProperties();
		}
		return confProperties.get(name);
	}
	
	
	static class InitWebPath{
		public String getRootPath() {
			String url = InitWebPath.class.getProtectionDomain().getCodeSource().getLocation().getFile();
			String filePath = "";
			try {
				filePath = java.net.URLDecoder.decode(url, "utf-8");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

			final String fileFlag = "file:";
			if (filePath.startsWith(fileFlag)) {
				filePath = filePath.substring(fileFlag.length());
			}
			final String applicationFlag = "WEB-INF";
			return filePath.substring(0, filePath.lastIndexOf(applicationFlag));
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值