Java J2EE读取配置文件

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));




		}




	}




}

 

posted @ 2018-10-18 14:06  有梦就能实现  阅读(569)  评论(0编辑  收藏  举报