java 4种方式读取配置文件 + 修改配置文件
版权声明:本文为博主原创文章,未经博主允许不得转载。
方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。
因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
具体举例如下:
//ServletContext.getRealPath(name)读取路径
privatevoid test1(HttpServletRequest request, HttpServletResponseresponse)
throwsServletException,IOException {
//response.setContentType("text/html;charset=utf-8");
String path = "/WEB-INF/jdbc_connection.properties"; //读取WEB-INF中的配置文件
String realPath = getServletContext().getRealPath(path);//getServletContext()相当于http://localhost/demo05
//所以后面的path只需要以应用demo/开头具体的部署目录路径即可,如上面的/web-in…
System.out.println(realPath);
InputStreamReader reader =new InputStreamReader(newFileInputStream(realPath),"utf-8");
Properties props = new Properties();
props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码
String jdbcConValue = props.getProperty("jdbc_con");
System.out.println(jdbcConValue);
System.out.println("加载src包下的资源------------------------");
path = "/WEB-INF/classes/com/test/servlet/jdbc_connection.properties"; //读取WEB-INF中的配置文件
realPath=getServletContext().getRealPath(path);
System.out.println(realPath);
reader = new InputStreamReader(new FileInputStream(realPath),"utf-8");
props.load(reader); //load个人建议还是用Reader来读,因为reader体系中有个InputStreamReader可以指定编码
jdbcConValue = props.getProperty("jdbc_con");
System.out.println("second::"+jdbcConValue);
}
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。
缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
- /**
 - * 获取指定配置文件中所以的数据
 - * @param propertyName
 - * 调用方式:
 - * 1.配置文件放在resource源包下,不用加后缀
 - * PropertiesUtil.getAllMessage("message");
 - * 2.放在包里面的
 - * PropertiesUtil.getAllMessage("com.test.message");
 - * @return
 - */
 - public static List<String> getAllMessage(String propertyName) {
 - // 获得资源包
 - ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim());
 - // 通过资源包拿到所有的key
 - Enumeration<String> allKey = rb.getKeys();
 - // 遍历key 得到 value
 - List<String> valList = new ArrayList<String>();
 - while (allKey.hasMoreElements()) {
 - String key = allKey.nextElement();
 - String value = (String) rb.getString(key);
 - valList.add(value);
 - }
 - return valList;
 - }
 
方式三:采用ClassLoader方式进行读取配置信息
- /**获取的是class的根路径下的文件
 - * 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
 - * 缺点:只能加载类classes下面的资源文件。
 - * 如果要加上路径的话:com/test/servlet/jdbc_connection.properties
 - */
 - private static void use_classLoador(){
 - //文件在class的根路径
 - InputStream is=TestJava.class.getClassLoader().getResourceAsStream("message.properties");
 - //获取文件的位置
 - String filePath=TestJava.class.getClassLoader().getResource("message.properties").getFile();
 - System.out.println(filePath);
 - //获取的是TestJava类所在的相对路径下 ,com/test/servlet/jdbc_connection.properties"
 - // InputStream is2=TestJava.class.getResourceAsStream("message.propertie");
 - BufferedReader br= new BufferedReader(new InputStreamReader(is));
 - Properties props = new Properties();
 - try {
 - props.load(br);
 - for (Object s : props.keySet())
 - System.out.println(s);
 - } catch (IOException e) { e.printStackTrace();}
 - }
 
方法4 getResouceAsStream
- BufferedReader br=new BufferedReader(
 - new InputStreamReader(XmlParserHandler.class.
 - getResourceAsStream("./rain.xml"), "GB2312"));// ./代表当前目录不写也可以
 - InputSource is=new InputSource(br);//数据源
 
方法5 PropertiesLoaderUtils工具类
- /**
 - * Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源
 - * 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启
 - */
 - private static void springUtil(){
 - Properties props = new Properties();
 - while(true){
 - try {
 - props=PropertiesLoaderUtils.loadAllProperties("message.properties");
 - for(Object key:props.keySet()){
 - System.out.print(key+":");
 - System.out.println(props.get(key));
 - }
 - } catch (IOException e) {
 - System.out.println(e.getMessage());
 - }
 - try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
 - }
 - }
 
修改Properties
- /**
 - * 传递键值对的Map,更新properties文件
 - *
 - * @param fileName
 - * 文件名(放在resource源包目录下),需要后缀
 - * @param keyValueMap
 - * 键值对Map
 - */
 - public static void updateProperties(String fileName,Map<String, String> keyValueMap) {
 - //getResource方法使用了utf-8对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,
 - //得到的往往不是我们想要的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的中文及空格路径。
 - String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();
 - Properties props = null;
 - BufferedWriter bw = null;
 - try {
 - filePath = URLDecoder.decode(filePath,"utf-8");
 - log.debug("updateProperties propertiesPath:" + filePath);
 - props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));
 - log.debug("updateProperties old:"+props);
 - // 写入属性文件
 - bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
 - props.clear();// 清空旧的文件
 - for (String key : keyValueMap.keySet())
 - props.setProperty(key, keyValueMap.get(key));
 - log.debug("updateProperties new:"+props);
 - props.store(bw, "");
 - } catch (IOException e) {
 - log.error(e.getMessage());
 - } finally {
 - try {
 - bw.close();
 - } catch (IOException e) {
 - e.printStackTrace();
 - }
 - }
 - }
 
java 4种方式读取配置文件 + 修改配置文件的更多相关文章
- 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
		
精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...
 - 远程访问Jupyter Notebook的两种方式:命令行和配置文件
		
远程访问Jupyter Notebook的两种方式:命令行和配置文件 相关配置:Ubuntu 16.04服务器,本地Win10,使用了Xshell,Xftp工具. 相关配置主要分为三步: 服务器上的J ...
 - 将图片base64格式转换为file对象并读取(两种方式读取)
		
两种方式读取,一种URL.createObjectURL,另一种fileReader var base64 = ` data:image/jpeg;base64,/9j/4AAQSkZJRgABA ...
 - java web工程读取及修改配置文件
		
这篇博客比自己讲解的详细: http://blog.sina.com.cn/s/blog_69398ed9010191jg.html 使用方法: 1)配置文件在web-info的class目录下,或者 ...
 - 第二种方式读取并显示HDFS中的内容
		
1.讀取HDFS内容的java客戶端代碼: package Hdfs; import java.io.InputStream; import java.net.URI; import org.apac ...
 - Java两种方式简单实现:爬取网页并且保存
		
注:如果代码中有冗余,错误或者不规范,欢迎指正. Java简单实现:爬取网页并且保存 对于网络,我一直处于好奇的态度.以前一直想着写个爬虫,但是一拖再拖,懒得实现,感觉这是一个很麻烦的事情,出现个小错 ...
 - 用类加载器的5种方式读取.properties文件
		
用类加载器的5中形式读取.properties文件(这个.properties文件一般放在src的下面) 用类加载器进行读取:这里采取先向大家讲读取类加载器的几种方法:然后写一个例子把几种方法融进去, ...
 - C# 读取与修改配置文件
		
System.Configuration.ConfigurationSettings.AppSettings["Key"]; 但是现在FrameWork2.0已经明确表示此属性已经 ...
 - .net core 读取、修改配置文件appsettings.json
		
.net core 设置读取JSON配置文件 appsettings.json Startup.cs 中 public class Startup { public Startup(IHostingE ...
 
随机推荐
- MSSQL-to-MySQL v5.3, 从MSSQL迁移到mySQL的最佳工具
			
将现有的MSSQL数据库迁移到MySQL数据库,尝试了很多种工具 MySQL Workbench / MSSQL to MySQL Export / DB Converter / openDBcopy ...
 - c# ContinueWith 用法
			
通过任务,可以指定在任务完成之后,应开始运行之后另一个特定任务.例如,一个使用前一个任务的结果的新任务,如果前一个任务失败了,这个任务就应执行一些清理工作.任务处理程序都不带参数或者带一个对象参数,而 ...
 - ios 消息通知
			
苹果的通知分为本地通知和远程通知,这里主要说的是远程通知 历史介绍 iOS 3 - 引入推送通知UIApplication 的 registerForRemoteNotificationTypes 与 ...
 - Linux运维(3年以内)
			
1.精通shell编程,熟练应用awk,sed,grep,strace,tcpdump等常用命令; 2.精通windows server,linux,mssql,mysql,熟悉网络,cisco,ju ...
 - October 16th Week 43rd Sunday 2016
			
Life is not a problem to be solved, but a reality to be experienced. 人生不是待解决的难题,而是等着我们去体验的现实. Life i ...
 - quartz 线程问题
			
2个任务一起使用quartz来调度,但是有一个任务总是会莫名其妙的暂停掉,排查了下,原来组内成员在写JOB任务时候,在JOB中写了个while(true) { 执行业务 休眠10分钟} 导 ...
 - Python爬虫Scrapy框架入门(1)
			
也许是很少接触python的原因,我觉得是Scrapy框架和以往Java框架很不一样:它真的是个框架. 从表层来看,与Java框架引入jar包.配置xml或.property文件不同,Scrapy的模 ...
 - jQuery和AngularJS的区别小分析
			
最近一直在研究angularjs,最大的感受就是它和之前的jQuery以及基于jQuery的各种库设计理念完全不同,如果不能认识到这点而对于之前做jQuery开发的程序员,去直接学习angularjs ...
 - [LeetCode] Best Time to Buy and Sell Stock
			
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
 - WPF 实现 DataGrid/ListView 分页控件
			
在WPF中,通常会选用DataGrid/ListView进行数据展示,如果数据量不多,可以直接一个页面显示出来.如果数据量很大,2000条数据,一次性显示在一个页面中,不仅消耗资源,而且用户体验也很糟 ...