Propreties使用时路径问题

来源:互联网 发布:大数据转型的企业 编辑:程序博客网 时间:2024/04/28 03:03

Propreties使用时路径问题

   ONE Goal ,ONE Passion !

Propretie一直在使用,昨天出了一个超级低级的错误,略显尴尬!

Propretie概述:

一般我们保存一些配置文件,最典型的当属jdbc配置文件.
形如:

driverClassName=com.mysql.jdbc.Driver    url=jdbc:mysql://localhost:3306/mydb    user=root    password=******

Properties放置位置:

1,放置到src的目录下
2,放置到src的子目录下

这里写图片描述

进入重点,如何读取Properties

1,使用ResourceBundle读取

//注意:getBundle("b")中的参数:    //b.Properties在src的根目录下写:   "b"或者"b.properties"    ResourceBundle rb_b = ResourceBundle.getBundle("b");    String name_b = rb_b.getString("name");    // a.Properties在src的子目录it下写: "it.a"或者"it.a.properties"    ResourceBundle rb_a = ResourceBundle.getBundle("it.a");        String name_a = rb_a.getString("name");

一定要注意配置文件在工程中的路径问题,一般配置文件我们直接写在src 的根目录下.


总结:
ResourceBundle读取时路径问题

a .当文件在src根目录下 getBundle(“文件名”); //getBundle(“b”)

b .当文件在src的子目录下 getBundle(“子目录的名称.文件名称”); //getBundle(“it.a”)

如果getBundle()中的格式写错了,就会报下面的错误

Can't find bundle for base name a, locale zh_CN

2,使用Properties类来读取

第一步: 首先获取Properties对象

Properties prop = new Properties();

第二步: 通过流来读取文件

    第一种:通过getResourceAsStream获取流来读取(最常见的一种)    InputStream is = 类名.class.getClassLoader().getResourceAsStream("a.properties");    第二种:通过常见流来读取    InputStream is = new FileInputStream("src//it//a.properties");

第三步 : 将流加载到Properties中

prop.load(is);

第四步: 通过key读取配置中的value

prop.get("name")或者prop.getProperty("name");

注意:
使用Properties来读取路径问题

a.当文件在src根目录下 b文件在src目录下

  getResourceAsStream("b.properties");

b.当文件在src的子目录下 a文件在src的子目录it下

getResourceAsStream("it//a.properties");

c.FileInputStream读取文件时,路径问题和操作File一样的.

FileInputStream("src//it//a.properties");

关联:File类详解
http://blog.csdn.net/fengltxx/article/details/51583977

ok !开车!

0 0
原创粉丝点击