Properties文件与ResourceBundle读取properties文件

xiaoxiao2021-02-28  32

博客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代码    InputStream in = lnew BufferedInputStream(new FileInputStream(name));   Properties p = new Properties();   p.load(in);   [java]  view plain  copy <span style="font-size:14px;"><span style="font-size:14px;">InputStream in = lnew BufferedInputStream(new FileInputStream(name));   Properties p = new Properties();   p.load(in);</span></span>  

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

Java代码    ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());    [java]  view plain  copy <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代码        ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");     String s = bundle.getString("URL");  System.out.println(s);  pURL = s;   [java]  view plain  copy <span style="font-size:14px;"><span style="font-size:14px;">      ResourceBundle bundle = ResourceBundle.getBundle("com.ihandy.smsoc.app.process");       String s = bundle.getString("URL");    System.out.println(s);    pURL = s;</span></span>  

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

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

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

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

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

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

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

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

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

Java代码    InputStream in = context.getResourceAsStream(path);   Properties p = new Properties();   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 /**          * 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);      }          
转载请注明原文地址: https://www.6miu.com/read-2624913.html

最新回复(0)