反射机制-属性配置文件-ResourceBundle资源绑定器获取配置文件

通过资源绑定器获取配置文件:

java.util包下提供了一个资源绑定器,便于获取属性配置文件中的内容。
使用以下这种方式的时候,属性配置文件xxx.properties必须放到类路径下src。

属性配置文件:直接在src类路径下创建

复制代码
mport java.util.ResourceBundle;
public class ResourceBundleTest {
    public static void main ( String[] args ) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");//文件名不可以加上:properties
        String url = bundle.getString("jdbc_url");
        String driver = bundle.getString("jdbc_driver");
        String user = bundle.getString("jdbc_user");
        String password = bundle.getString("jdbc_password");
        System.out.println("mysql驱动:"+driver);
        System.out.println("mysql解析地址:"+url);
        System.out.println("mysql用户名:"+user);
        System.out.println("mysql密码:"+password);

    }
}
复制代码

属性配置文件更换包以后的类路径需要一起写道资源绑定器中:

以类路径的方式去找到该属性配置文件;属性配置文件不能添加拓展名

 ResourceBundle bundle = ResourceBundle.getBundle("com/xzit/platfrom/test/jdbc");//文件名不能加上:properties

 

 

IO+properties:直接以流的形式返回属性配置文件:

复制代码
import java.io.FileReader;
import java.io.InputStream;
import java.util.Properties;

public class IoPropertiesTest {
    public static void main(String[] args) throws Exception{

        // 直接以流的形式返回。
        InputStream reader = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("classinfo2.properties");

        Properties pro = new Properties();
        pro.load(reader);
        reader.close();
        // 通过key获取value
        String className = pro.getProperty("className");
        System.out.println(className);
    }
}
复制代码

 

posted @   280887072  阅读(83)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示