java读取配置文件(转)
转载:http://blog.csdn.net/gaogaoshan/article/details/8605887
方式一:采用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读取配置文件(转)的更多相关文章
- java读取配置文件的几种方法
java读取配置文件的几种方法 原文地址:http://hbcui1984.iteye.com/blog/56496 在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配 ...
- Java读取配置文件的方式
Java读取配置文件的方式-笔记 1 取当前启动文件夹下的配置文件 一般来讲启动java程序的时候.在启动的文件夹下会有配置文件 classLoader.getResource(&qu ...
- java读取配置文件
java 读取文件可以用字节流和字符流. 由于一个汉字占两个字节,所以如果配置文件中有汉字,用字节流读取,会出现乱码. 用字符流则不会出现乱码. 配置文件 b.properties 文件如下: fam ...
- Java 读取配置文件数据
Properties类 Properties类,是一个工具类,包含在java.util包中. 功能:可以保存持久的属性,通常用来读取配置文件或者属性文件,将文件中的数据读入properties对象中, ...
- java读取配置文件方法以及工具类
第一种方式 : java工具类读取配置文件工具类 只是案例代码 抓取异常以后的代码自己处理 import java.io.FileNotFoundException; import java.io. ...
- java读取配置文件内容
利用com.typesafe.config包实现 <dependency> <groupId>com.typesafe</groupId> <artifact ...
- spring boot使用java读取配置文件,DateSource测试,BomCP测试,AnnotationConfigApplicationContext的DataSource注入
一.配置注解读取配置文件 (1)@PropertySource可以指定读取的配置文件,通过@Value注解获取值 实例: @PropertySource(val ...
- 使用Java读取配置文件
实现起来,相对比较简单,留个备案吧,废话也不多说,请看代码: package com.jd.***.config; import org.junit.*; import java.io.IOExcep ...
- 转:java读取配置文件的几种方法
转自: http://www.iteye.com/topic/56496 在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据笔者工作中用到的读取配置文件的方法小小 ...
随机推荐
- java.util.HashMap 解析
HashMap 是我们经常使用的一种数据结构.工作中会经常用到,面试也会总提到这个数据结构,找工作的时候,”HashTable 和HashMap的区别“被问到过没有? 本文会从原理,JDK源码,项目使 ...
- Rxjava2.0 链式请求异常处理
使用Rxjava2.0的过程中,难免会遇到链式请求,而链式请求一般都是第一个抛异常,那么后面的请求都是不会走的.现在来讨论一下链式请求的一种异常处理方法.例如: 一个登录-->通过登录返回的to ...
- SQL-ORDER BY 多字段排序(升序、降序)
ORDER BY _column1, _column2; /* _column1升序,_column2升序 */ ORDER BY _column1, _column2 DESC; /* _col ...
- 使用Loadrunner进行文件的上传和下载
最近使用loadrunner中需要录制文件的上传和下载,上传功能模块利用录制可以直接实现,下载无法实现,在网上找到了一段代码,自己动手试验了下,发现没有用 辛苦找到的,还是记录下吧 (1)LoadRu ...
- php求斐波那契数列
<?php function feibonaqi(){ //参数$num表示为第$num个数之前的所有斐波那契数列 $arr = array(); //定义一个空变量用来存放斐波那契数列的数组 ...
- 两名技术人员,历经8小时Piranha Games成功集成Xsolla
w=580&h=304" alt="" width="580" height="304" style="max- ...
- sql中判断某个字符串是否包含一个字符串
如果想从SQL Server中查询包含某个关键字的东东,怎么查询呢? 一般有两个方法: 1.用like——select * from tablename where field1 like like ...
- Java Collection之Queue具体解释及用途
Queue是一种常见的数据结构,其主要特征在于FIFO(先进先出),Java中的Queue是这样定义的: public interface Queue<E> extends Collect ...
- Linux-查看C语言手册及man的特殊用法
man命令可以查看c语言库函数的函数原型, 比如 $ man malloc 如果显示 "No manual entry for malloc", 则需要安装 "man-p ...
- Ffmpeg 视频教程 向视频中添加文字
Ffmpeg支持添加文字功能,具体如何将文字叠加到视频中的每一张图片,FFmpeg调用了文字库FreeSerif.ttf.当我们 用到ffmpeg 添加文字功能时 我们需要先下载改文字库,下载地址是h ...