properties文件及ResourceBundle读取properties文件分析

来源:互联网 发布:天天看盘软件怎么样 编辑:程序博客网 时间:2024/06/05 16:16

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



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

Java代码 复制代码 收藏代码
  1. ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());   



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




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

Java代码 复制代码 收藏代码
  1. InputStream in = new BufferedInputStream(new FileInputStream(name));   
  2. ResourceBundle rb = new PropertyResourceBundle(in);   



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

Java代码 复制代码 收藏代码
  1. InputStream in = 类名.class.getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   


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

Java代码 复制代码 收藏代码
  1. InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   



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

Java代码 复制代码 收藏代码
  1. InputStream in = ClassLoader.getSystemResourceAsStream(name);   
  2. Properties p = new Properties();   
  3. p.load(in);   



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

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


三、使用ResourceBundle读取配置文件


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

12345
#数据库配置信息DRIVER=com.mysql.jdbc.DriverURL=jdbc:mysql://localhost:3306/cnsuser=testpassword=test



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

12345678910111213141516171819
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 }}


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

/**         * Converts the given <code>bundleName</code> to the form required         * by the {@link ClassLoader#getResource ClassLoader.getResource}         * method by replacing all occurrences of <code>'.'</code> in         * <code>bundleName</code> with <code>'/'</code> and appending a         * <code>'.'</code> and the given file <code>suffix</code>. For         * example, if <code>bundleName</code> is         * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code>         * is <code>"properties"</code>, then         * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned.         *         * @param bundleName         *        the bundle name         * @param suffix         *        the file type suffix         * @return the converted resource name         * @exception NullPointerException         *         if <code>bundleName</code> or <code>suffix</code>         *         is <code>null</code>         */        public final String toResourceName(String bundleName, String suffix) {            StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());            sb.append(bundleName.replace('.', '/')).append('.').append(suffix);            return sb.toString();        }最终还是用classloader进行资源文件的加载:else if (format.equals("java.properties")) {                final String resourceName = toResourceName0(bundleName, "properties");                if (resourceName == null) {                    return bundle;                }                final ClassLoader classLoader = loader;                final boolean reloadFlag = reload;                InputStream stream = null;                try {                    stream = AccessController.doPrivileged(                        new PrivilegedExceptionAction<InputStream>() {                            public InputStream run() throws IOException {                                InputStream is = null;                                if (reloadFlag) {                                    URL url = classLoader.getResource(resourceName);                                    if (url != null) {                                        URLConnection connection = url.openConnection();                                        if (connection != null) {                                            // Disable caches to get fresh data for                                            // reloading.                                            connection.setUseCaches(false);                                            is = connection.getInputStream();                                        }                                    }                                } else {                                    is = classLoader.getResourceAsStream(resourceName);                                }                                return is;                            }                        });                } catch (PrivilegedActionException e) {                    throw (IOException) e.getException();                }                if (stream != null) {                    try {                        bundle = new PropertyResourceBundle(stream);                    } finally {                        stream.close();                    }                }            } else {                throw new IllegalArgumentException("unknown format: " + format);            }并且最终 还是使用了java类Properties public PropertyResourceBundle (InputStream stream) throws IOException {        Properties properties = new Properties();        properties.load(stream);        lookup = new HashMap(properties);    }



0 0
原创粉丝点击