Properties文件与ResourceBundle读取properties文件

博客1:Java中resourceBundle和Properties的区别

第一种办法
InputStream is = Test.class.getResourceAsStream("DbConfig.properties");
Properties p = new Properties();
p.load(is);
System.out.println(p.get("jndi"));
Test.class要放在DbConfig.properties同一目录??? 这句话需要待测试.
第二种办法
private String BUNDLE_NAME = "com.newland.alarmquery.resource.DbConfig";///不要加上扩展名
ResourceBundle resource_bundle = ResourceBundle.getBundle(BUNDLE_NAME);
jndi=resource_bundle.getString("jndi");
System.out.println(p.get("jndi"));
一般来说,ResourceBundle类通常是用于针对不同的语言来使用的属性文件。
而如果你的应用程序中的属性文件只是一些配置,并不是针对多国语言的目的。那么使用Properties类就可以了。
通常可以把这些属性文件放在某个jar文件中。然后,通过调用class的getResourceAsStream方法,来获得该属性文件的流对象,再用Properties类的load方法来装载。
有时候有些简单的配置文件可以没必要使用xml,其实ResourceBundle类就已经做的很好的。它甚至可以搜索到classpath里的jar文件中一些properties文件。
例如在jar文件中的根目录放置一个文件:DbConfig.properties,然后只要这个jar文件在classpath里。就可以使用这样的语句来获得一些属性

【需要注意的地方:】
1.ResourceBundle.getBundle(String arg0)中的参数arg0必须包含属性文件的完整路径。
2.将属性文件(例如config.properties)和读取文件在一起;
属性文件和读取的文件要放在一起,如果要分开这两个文件呢?那么我们自己可以自己建立一个目录,将属性文件放到其下,再将该目录设置为classloader加载的目录(加入类路径中)则可,如下:
1、在项目下建一文件夹,路径随意,名字任意(这为:properties)。
2、(Eclipse中)选择项目->Properties->java Build Path->Libraries->Add 
Class Folder,将properties文件加入类路径即可(或者手动在.classpath文件中加入:<classpathentry kind="lib" path="properties"/>)。然后直接用 
ResourceBundle.getBundle("config");则可读取 
properties/config.properties文件的内容。
3.resourceBundle.getBundle(args0)中传入的参数为资源文件的basename.且不用加.properties文件后缀。
如资源文件名为:myres_zh_CN.properties或myres.properties则只需要传入myres就可以 了。
4.ResourceBundle这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。

博客2:

一、properties文件介绍

 java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是 "键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。

properties文件示例:

# 以下为服务器、数据库信息

dbPort = localhost 

databaseName = mydb 

dbUserName = root 

dbPassword = root 

# 以下为数据库表信息

dbTable = mytable 

# 以下为服务器信息

ip = 192.168.0.9 

上面的文件中我们假设该文件名为:test.properties 文件。其中# 开始的一行为注释信息;在等号“= ”左边的我们称之为key ;等号“= ”右边的我们称之为value 。(其实就是我们常说的键- 值对)key 应该是我们程序中的变量。而value 是我们根据实际情况配置的。


二、java常见读取properties文件方法


1、使用java.util.Properties类的load()方法示例:

Java代码  复制代码   收藏代码
  1. InputStream in = lnew BufferedInputStream(new FileInputStream(name));   
  2. Properties p = new Properties();   
  3. p.load(in);  
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = lnew BufferedInputStream(new FileInputStream(name));   
  2. Properties p = new Properties();   
  3. p.load(in);</span></span>  



2、使用java.util.ResourceBundle类的getBundle()方法
示例:

Java代码  复制代码   收藏代码
  1. ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());   
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault()); </span></span>  



用ResourceBundle读取.properties文件可避免路径问题 
            我在jar里读取.properties文件时,总是找不到文件路径,后来用ResourceBundle读取.properties文件即可避免路径问题,代码如下:
     

//process为文件名,切记不要加 .properties, URL是文件里的键名 

Java代码  复制代码   收藏代码
  1.     ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");  
  2.    String s = bundle.getString("URL");  
  3. System.out.println(s);  
  4. pURL = s;  
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">      ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");  
  2.      String s = bundle.getString("URL");  
  3.   System.out.println(s);  
  4.   pURL = s;</span></span>  




3、使用java.util.PropertyResourceBundle类的构造函数
示例: 

Java代码  复制代码   收藏代码
  1. InputStream in = new BufferedInputStream(new FileInputStream(name));   
  2. ResourceBundle rb = new PropertyResourceBundle(in);   
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = new BufferedInputStream(new FileInputStream(name));   
  2. ResourceBundle rb = new PropertyResourceBundle(in); </span></span>  



4、使用class变量的getResourceAsStream()方法
示例:
 

Java代码  复制代码   收藏代码
  1. InputStream in = 类名.class.getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = 类名.class.getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in); </span></span>  


5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法示例:

Java代码  复制代码   收藏代码
  1. InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in); </span></span>  



6、使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法示例:

Java代码  复制代码   收藏代码
  1. InputStream in = ClassLoader.getSystemResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   
[java]  view plain  copy
  1. <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = ClassLoader.getSystemResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in); </span></span>  



7、Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法示例:

Java代码  复制代码   收藏代码
  1. InputStream in = context.getResourceAsStream(path);   
  2. Properties p = new Properties();   
  3. p.load(in);   


三、使用ResourceBundle读取配置文件


假如我现在有一个数据库的配置文件,我将它写为资源文件的样式,则为:

1
2
3
4
5
#数据库配置信息
DRIVER=com.mysql.jdbc.Driver
URL=jdbc:mysql://localhost:3306/cns
user=test
password=test



接下来,我们使用ResourceBundle类处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package Forum;
 
import java.util.*;
 
public class RedProFile {
	 public static void main(String[] a){
	String resourceFile = "Forum.CNS";    
//	        创建一个默认的ResourceBundle对象   
//	        ResourceBundle会查找包Forum下的CNS.properties的文件   
//	        Forum是资源的包名,它跟普通java类的命名规则完全一样:   
//	        - 区分大小写   
//	        - 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样   
//	        - 资源文件必须位于指定包的路径之下(位于所指定的classpath中)   
//            假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
//            如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。
	ResourceBundle rb = ResourceBundle.getBundle(resourceFile);
	System.out.println(rb.getString("DRIVER"));//这里是分大小写的,嘿嘿输出值为jdbc:mysql://localhost:3306/cns
	 }
}


可以这样写的原因,看下面源码

[java]  view plain  copy
  1. /** 
  2.          * Converts the given <code>bundleName</code> to the form required 
  3.          * by the {@link ClassLoader#getResource ClassLoader.getResource} 
  4.          * method by replacing all occurrences of <code>'.'</code> in 
  5.          * <code>bundleName</code> with <code>'/'</code> and appending a 
  6.          * <code>'.'</code> and the given file <code>suffix</code>. For 
  7.          * example, if <code>bundleName</code> is 
  8.          * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code> 
  9.          * is <code>"properties"</code>, then 
  10.          * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned. 
  11.          * 
  12.          * @param bundleName 
  13.          *        the bundle name 
  14.          * @param suffix 
  15.          *        the file type suffix 
  16.          * @return the converted resource name 
  17.          * @exception NullPointerException 
  18.          *         if <code>bundleName</code> or <code>suffix</code> 
  19.          *         is <code>null</code> 
  20.          */  
  21.         public final String toResourceName(String bundleName, String suffix) {  
  22.             StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());  
  23.             sb.append(bundleName.replace('.''/')).append('.').append(suffix);  
  24.             return sb.toString();  
  25.         }  
  26.   
  27.   
  28.   
  29.   
  30. 最终还是用classloader进行资源文件的加载:  
  31.   
  32. else if (format.equals("java.properties")) {  
  33.                 final String resourceName = toResourceName0(bundleName, "properties");  
  34.                 if (resourceName == null) {  
  35.                     return bundle;  
  36.                 }  
  37.                 final ClassLoader classLoader = loader;  
  38.                 final boolean reloadFlag = reload;  
  39.                 InputStream stream = null;  
  40.                 try {  
  41.                     stream = AccessController.doPrivileged(  
  42.                         new PrivilegedExceptionAction<InputStream>() {  
  43.                             public InputStream run() throws IOException {  
  44.                                 InputStream is = null;  
  45.                                 if (reloadFlag) {  
  46.                                     URL url = classLoader.getResource(resourceName);  
  47.                                     if (url != null) {  
  48.                                         URLConnection connection = url.openConnection();  
  49.                                         if (connection != null) {  
  50.                                             // Disable caches to get fresh data for  
  51.                                             // reloading.  
  52.                                             connection.setUseCaches(false);  
  53.                                             is = connection.getInputStream();  
  54.                                         }  
  55.                                     }  
  56.                                 } else {  
  57.                                     is = classLoader.getResourceAsStream(resourceName);  
  58.                                 }  
  59.                                 return is;  
  60.                             }  
  61.                         });  
  62.                 } catch (PrivilegedActionException e) {  
  63.                     throw (IOException) e.getException();  
  64.                 }  
  65.                 if (stream != null) {  
  66.                     try {  
  67.                         bundle = new PropertyResourceBundle(stream);  
  68.                     } finally {  
  69.                         stream.close();  
  70.                     }  
  71.                 }  
  72.             } else {  
  73.                 throw new IllegalArgumentException("unknown format: " + format);  
  74.             }  
  75.   
  76. 并且最终 还是使用了java类Properties  
  77.   
  78.  public PropertyResourceBundle (InputStream stream) throws IOException {  
  79.         Properties properties = new Properties();  
  80.         properties.load(stream);  
  81.         lookup = new HashMap(properties);  
  82.     }  
  83.   
  84.   
  85.   
  86.   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值