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. 自然语言处理--jieba和gensim的分词功能

    一.jieba分词功能 1.主要模式 支持三种分词模式: 精确模式,试图将句子最精确地切开,适合文本分析: 全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义: 搜索引擎模 ...

  2. “网红架构师”解决你的Ceph 运维难题

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由Tstack发表于云+社区专栏 本文为长篇连续剧,将分多个篇幅发表,主要介绍了从动手部署环境到后期运营故障处理过程中常见的问题,内容由 ...

  3. 软件架构设计学习总结(3):QQ空间技术架构之详解

    QQ空间作为腾讯海量互联网服务产品,经过近七年的发展,实现了从十万级到亿级同时在线的飞跃.在这个过程中,QQ空间团队遇到了哪些技术挑战?其站点前后台架构随着业务规模的变化又进行了怎样的演进与变迁?成长 ...

  4. python 使用 matplotlib.pyplot来画柱状图和饼图

    导入包 import matplotlib.pyplot as plt 柱状图 最简柱状图 # 显示高度 def autolabel(rects): for rect in rects: height ...

  5. 【LeetCode题解】3_无重复字符的最长子串(Longest-Substring-Without-Repeating-Characters)

    目录 描述 解法一:暴力枚举法(Time Limit Exceeded) 思路 Java 实现 Python 实现 复杂度分析 解法二:滑动窗口(双指针) 思路 Java 实现 Python 实现 复 ...

  6. Ant Trip(区别于二分匹配中最小路径覆盖的一笔画问题)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3018 题目: Problem Description Ant Country consist of ...

  7. 基于卷积神经网络的手写数字识别分类(Tensorflow)

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  8. 文档数据库MongoDB

    MongoDB是一个基于分布式文件存储的文档式数据库.其由C++编写, 旨在为Web应用提供可扩展的高性能数据存储解决方案. MongoDB中每条数据记录被作为一个文档存储,文档由集合(collect ...

  9. 异步上传文件,jquery+ajax,显示进度条

    根据网上的资料,做了很多修改,结果发现使用ajax上传数据时若要监听xhr.upload.addEventListener("progress",functiion(e),fals ...

  10. React多页面应用脚手架-v1.3.0

    react-multi-page-app是一个基于react和webpack的多页面应用架构,通过编译生成对应目录结构清晰的静态页面,实现多页面便捷开发维护.1.3.0 版本对项目整体做了一个全面的升 ...