Java中资源文件的使用(properties)

properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties文件中,可以用"#"来作注释。


 

一、资源文件

例子:在项目src目录下创建资源文件temp.properties。

#学号
id=001
#姓名
name=lurenjia
#年龄
age=18

二、Java代码中读取资源文件

步骤:

  1、初始化Properties对象

  2、加载资源文件

  3、通过键名,获取值

例子:读取上面创建的temp.properties。

    public static void main(String[] args) throws IOException {
        //1.加载对象
        Properties pros = new Properties();
        //2.加载src目录下的资源文件
        pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
        //3.通过键名,获取值
        String temp1 = pros.getProperty("id");
        String temp2 = pros.getProperty("name");
        String temp3 = pros.getProperty("age");
        System.out.println(temp1+"\t"+temp2+"\t"+temp3);
    }

运行结果:

控制台输出:
001 lurenjia 18

 

posted @ 2022-12-23 19:41  在博客做笔记的路人甲  阅读(294)  评论(0编辑  收藏  举报