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

		}

	}

}

Java J2EE读取配置文件的更多相关文章

  1. java中读取配置文件ResourceBundle和Properties两种方式比较

    今天在开发的时候,需要把一些信息放到配置文件中,方便后续的修改,注意到用的是ResourceBundle读取配置文件的方式,记得之前也见过使用Properties的方式,就比较好奇这两种方式的区别,网 ...

  2. java web 读取配置文件两种方法

    package com.tsinghua.getDataBaseConn; import java.io.IOException;import java.io.InputStream;import j ...

  3. java后台读取配置文件

    前几天开发时遇到一个问题,在后台读取配置文件的时候无法读取属性值,于是上网查了查,现在在这分享给大家: 先附上代码吧: package com.shafei.util; import java.io. ...

  4. Java中读取配置文件中的内容,并将其赋值给静态变量的方法

    应用场景 项目开发中某个功能需要抽取成方法写成一个工具类,提供给别人使用.写过工具类的人都知道,工具类中的方法一般都是静态方法,可以直接使用类名点方法名调用, 使用很方便,比如判断某个对象是否为空的方 ...

  5. 在java中读取配置文件信息

    public class PropertyUtil { public static final Properties PROP = new Properties(); /** * 读取配置文件的内容( ...

  6. java中读取配置文件的方法

    转自:http://blog.csdn.net/stypace/article/details/38414871 一.使用org.apache.commons.configuration 需要使用的是 ...

  7. 转载:Java项目读取配置文件时,FileNotFoundException 系统找不到指定的文件,System.getProperty("user.dir")的理解

    唉,读取个文件,也就是在项目里面去获得配置文件的目录,然后,变成文件,有事没事,总是出个 FileNotFoundException  系统找不到指定的文件,气死人啦. 还有就是:System.get ...

  8. java中读取配置文件

    若是Javaweb项目,项目运行于tomcat或其他容器时,可以使用下面方式来获取文件的输入流 1.当属性文件放在src下面时 InputStream is = Thread.currentThrea ...

  9. java中读取配置文件中的数据

    1.先在项目中创建一个包(如:config),再创建一个配置文件(如:a.properties),添加配置信息如下:比如:name=kakaage=28 2.代码:import java.io.IOE ...

随机推荐

  1. node mysql插入中文时报错

    一开始以为是前端传参.数据类型的问题,于是就直接把sql语句中的参数直接改成字符串值,但发现还是报500错误. 所以,这就排除了前端的问题. 剩下的就是数据库了,发现我的表设置有问题.凡是有中文数据的 ...

  2. redisTemplate实现轻量级消息队列, 异步处理excel并实现腾讯云cos文件上传下载

    背景 公司项目有个需求, 前端上传excel文件, 后端读取数据.处理数据.返回错误数据, 最简单的方式同步处理, 客户端上传文件后一直阻塞等待响应, 但用户体验无疑很差, 处理数据可能十分耗时, 没 ...

  3. TCP滑动窗口

    TCP利用滑动窗口实现流量控制基本的数据单位不是数据段,而是字节 滑动窗口本质上是描述接受方(本地)的TCP数据报缓冲区大小的数据,发送方根据这个数据来计算自己最多能发送多长的数据.如果发送方收到接受 ...

  4. c++中友元机制

    友元的概念:遵循一定规则而使对象以外的软件系统能够不经过消息传递方式而直接访问对象内封装的数据成员的技术方法便是友元. 只要将外界的某个对象说明为一个类的友元,那么这个外界对象就可以访问这个类对象中的 ...

  5. android studio 断网使用

  6. javascript学习之路之元素获取和设置属性

    收拾心情,学习学习js!总结下自己的学习所得! 现有的有三种方法可以获取元素的节点,分别是通过元素ID,通过标签名和类名来获取的 1.GetElmentById:将返回一个与那个有给定ID属性的值的元 ...

  7. 【4】 .net MVC使用Session验证用户登录

    用最简单的Session方式记录用户登录状态 1.添加DefaultController控制器,重写OnActionExecuting方法,每次访问控制器前触发 public class Defaul ...

  8. oracle安装与备份导入

    win10安装oracle因运行版本问题导致安装时提示错误(可能win10未被甲骨文公司认证)  跳过的问题 需要更改配置文件: 配置位置在 : 具体操作如下图: 在安装时win10跳过了 许是因为环 ...

  9. leetcode916

    单词子集 我们给出两个单词数组 A 和 B.每个单词都是一串小写字母. 现在,如果 b 中的每个字母都出现在 a 中,包括重复出现的字母,那么称单词 b是单词 a 的子集. 例如,“wrr” 是 “w ...

  10. 漫画 | Java多线程与并发(一)

    1.什么是线程? 2.线程和进程有什么区别? 3.如何在Java中实现线程? 4.Java关键字volatile与synchronized作用与区别? volatile修饰的变量不保留拷贝,直接访问主 ...