用类加载器的方式管理资源和配置文件

来源:互联网 发布:ios程序员工资待遇 编辑:程序博客网 时间:2024/05/22 02:08

有些小的文件不需要使用数据库保存, 直接使用文本文件保存在硬盘上, 需要用的时候,直接从文本文件中读取,如何读取呢?

使用类加载器加载这些文件。

 

使用方法:

InputStream ips = 类名.class.getClassLoader().getResourceAsStream("配置文件的路径“);

例如:InputStream ips = TestReflect2.class.getClassLoader().getResourceAsStream("itcast/cn/Reflect/config.properties");

 

注意:ClassLoader加载配置文件时,它是在classpath 的根路径下搜索,所以在填写配置文件的路径时要特别注意。bin是classpath 根路径,在配置文件钱要加上完整的包名。

 

另一种方法:不使用类加载器,使用自身类去加载

InputStream ips = 类名.class.getResourceAsStream("配置文件的路径");

例如:InputStream ips = TestReflect2.class.getResourceAsStream("config.properties"); 

这里的配置文件的 路径是相对于类TestReflect2 的,TestReflect2已经在cn.itcast.Reflect包下,就不需要写上包名。

 

程序实例:

InputStream ips = TestReflect2.class.getClassLoader().getResourceAsStream("itcast/cn/Reflect/config.properties");

Properties prop = new Properties();    // Properties 是可以保存或从流中加载, 它就相当于Map , 存储的是键和值的属性列

prop.load(ips);    //从流中将数据加载进来

prop.getProperty(String key)    // 获得指定key的value值

 

在获得value值之后,可以使用反射Class.forName(value).newInstance(); 创建一对象