Java读取properties配置文件的8种方式汇总

目录
  • 一、前言
  • 二、Properties类
  • 三、Properties常用方法实践
  • 四、Java写入Properties
  • 五、Java读取Properties
  • 六、Properties配合Spring框架使用
  • 七、完整代码
  • 总结

一、前言

在做Java项目开发过程中,涉及到一些数据库服务连接配置、缓存服务器连接配置等,通常情况下我们会将这些不太变动的配置信息存储在以 .properties 结尾的配置文件中。当对应的服务器地址或者账号密码信息有所变动时,我们只需要修改一下配置文件中的信息即可。同时为了让Java程序可以读取 .properties配置文件中的值,JavaJDK中提供了java.util.Properties类可以实现读取配置文件。

二、Properties类

Properties 类位于 java.util.Properties中,是Java 语言的处理配置文件所使用的类,其中的xxx.Properties类主要用于集中的持久存储Java的配置文件内容,可以读取后缀是.properties.cfg的配置文件。

Properties继承了Hashtable 类,以Map 的形式进行放置值,put(key,value)get(key),文本注释信息可以用"#"来注释。

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

Properties 文件内容的格式是:键=值 形式,Key值不能够重复。 例如:

jdbc.driver=com.mysql.jdbc.Driver

Properties类的继承关系图:

Properties类的源码关系图:

主要方法介绍:

它提供了几个核心的方法:

  • getProperty ( String key): 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
  • load ( InputStream inStream): 从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
  • setProperty ( String key, String value) : 调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
  • store ( OutputStream out, String comments): 以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
  • clear (): 清除所有装载的 键 - 值对。该方法在基类中提供。

三、Properties常用方法实践

Properties类我们从文件的写入和读取来实践其具体用法,下面演示练习将以下数据库配置信息写入到jdbc.properties文件中

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

项目目录结构如下

四、Java写入Properties

Properties类调用setProperty方法将键值对保存到内存中,此时可以通过getProperty方法读取,propertyNames方法进行遍历,但是并没有将键值对持久化到属性文件中,故需要调用store方法持久化键值对到属性文件中。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @desc:  写入Mysql数据库了连接信息到jdbc.properties中
 * @author: cao_wencao
 * @date: 2020-12-29 13:41
 */
public class PropertiesStoreTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream("src/main/resources/jdbc.properties");
            properties.setProperty("jdbc.driver", "com.mysql.jdbc.Driver");
            properties.setProperty("jdbc.url","jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8" );
            properties.setProperty("jdbc.username", "root");
            properties.setProperty("jdbc.password", "123456");

            // 保存键值对到文件中
            properties.store(output, "Thinkingcao modify");

        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出结果,在resources目录下多一个文件jdbc.properties,内容如下:

#Thinkingcao modify
#Tue Dec 29 13:43:48 CST 2020
jdbc.url=jdbc\:mysql\://localhost\:3306/mybatis?characterEncoding\=utf8
jdbc.username=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.password=123456

五、Java读取Properties

Java读取Properties文件的方法有很多,下面介绍8种方式,分别读取resource目录下的jdbc.properties和resource/config/application.properties。

application.properties文件内容如下

minio.endpoint=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=demo

1. 从当前的类加载器的getResourcesAsStream来获取

/**
     * 1. 方式一
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("jdbc.url");
        System.out.println("property = " + property);
    }

2. 从当前的类加载器的getClassLoader().getResourcesAsStream来获取

 /**
     * 2. 方式二
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

3. 使用Class类的getSystemResourceAsStream静态方法 和使用当前类的ClassLoader是一样的

 /**
     * 3. 方式三
     * 使用Class类的getSystemResourceAsStream方法 和使用当前类的ClassLoader是一样的
     * InputStream inputStream = ClassLoader.getSystemResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

4. 使用Spring-core包中的ClassPathResource读取

    /**
     * 4. 方式四
     * Resource resource = new ClassPathResource(path)
     *
     * @throws IOException
     */
    @Test
    public void test4() throws IOException {
        Resource resource = new ClassPathResource("config/application.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

5. 从文件中读取,new BufferedInputStream(InputStream in)

/**
     * 5. 方式五
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * BufferedInputStream继承自InputStream
     * InputStream inputStream = new BufferedInputStream(new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream("src/main/resources/config/application.properties"));
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

6.从文件中读取,new FileInputStream(String name)

/**
     * 6. 方式六
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * FileInputStream继承自InputStream
     * InputStream inputStream = new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
        InputStream inputStream = new FileInputStream("src/main/resources/config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

7. 使用PropertyResourceBundle读取InputStream流

 /**
     * 7. 方式七
     * 使用InputStream流来进行操作ResourceBundle,获取流的方式由以上几种。
     * ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
     * @throws IOException
     */
    @Test
    public void test7() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String s = keys.nextElement();
            System.out.println(s + " = " + resourceBundle.getString(s));
        }
    }

8. 使用ResourceBundle.getBundle读取

 /**
     * 8. 方式八
     * ResourceBundle.getBundle的路径访问和 Class.getClassLoader.getResourceAsStream类似,默认从根目录下读取,也可以读取resources目录下的文件
     * ResourceBundle rb = ResourceBundle.getBundle("b") //不需要指定文件名的后缀,只需要写文件名前缀即可
     */
    @Test
    public void test8(){
        //ResourceBundle rb = ResourceBundle.getBundle("jdbc"); //读取resources目录下的jdbc.properties
        ResourceBundle rb2 = ResourceBundle.getBundle("config/application");//读取resources/config目录下的application.properties
        for(String key : rb2.keySet()){
            String value = rb2.getString(key);
            System.out.println(key + ":" + value);
        }

    }

输出结果:

minio.endpoint:http://localhost:9000
minio.bucketName:demo
minio.secretKey:minioadmin
minio.accessKey:minioadmin

六、Properties配合Spring框架使用

加载.properties方式一

<!-- 1.加载 jdbc.properties 配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>

除了上面这种方式之外,还有下面这种List集合的方式

加载.properties方式二

 <!-- 4.引入外部配置文件 由于后期可能会引入多个配置文件 所以采用list的形式 -->
    <bean id="propertyPlaceholder"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/config/jdbc.properties</value>
                <value>classpath:/config/application.properties</value>
            </list>
        </property>
    </bean>

七、完整代码

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @desc: Properties读取配置文件属性值的方式
 * @author: cao_wencao
 * @date: 2020-12-29 10:08
 */
public class PropertiesTest {

    /**
     * 1. 方式一
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("jdbc.url");
        System.out.println("property = " + property);
    }

    /**
     * 2. 方式二
     * 从当前的类加载器的getResourcesAsStream来获取
     * InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 3. 方式三
     * 使用Class类的getSystemResourceAsStream方法 和使用当前类的ClassLoader是一样的
     * InputStream inputStream = ClassLoader.getSystemResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test4() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 4. 方式四
     * Resource resource = new ClassPathResource(path)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        Resource resource = new ClassPathResource("config/application.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 5. 方式五
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * BufferedInputStream继承自InputStream
     * InputStream inputStream = new BufferedInputStream(new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream("src/main/resources/config/application.properties"));
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 6. 方式六
     * 从文件中获取,使用InputStream字节,主要是需要加上当前配置文件所在的项目src目录地址。路径配置需要精确到绝对地址级别
     * FileInputStream继承自InputStream
     * InputStream inputStream = new FileInputStream(name)
     * 这种方法读取需要完整的路径,优点是可以读取任意路径下的文件,缺点是不太灵活
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
        InputStream inputStream = new FileInputStream("src/main/resources/config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 7. 方式七
     * 使用InputStream流来进行操作ResourceBundle,获取流的方式由以上几种。
     * ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
     * @throws IOException
     */
    @Test
    public void test7() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String s = keys.nextElement();
            System.out.println(s + " = " + resourceBundle.getString(s));
        }
    }

    /**
     * 8. 方式八
     * ResourceBundle.getBundle的路径访问和 Class.getClassLoader.getResourceAsStream类似,默认从根目录下读取,也可以读取resources目录下的文件
     * ResourceBundle rb = ResourceBundle.getBundle("b") //不需要指定文件名的后缀,只需要写文件名前缀即可
     */
    @Test
    public void test8(){
        //ResourceBundle rb = ResourceBundle.getBundle("jdbc"); //读取resources目录下的jdbc.properties
        ResourceBundle rb2 = ResourceBundle.getBundle("config/application");//读取resources/config目录下的application.properties
        for(String key : rb2.keySet()){
            String value = rb2.getString(key);
            System.out.println(key + ":" + value);
        }

    }

    /**
     * 单独抽取的方法,用户检测能否正确操纵Properties
     *
     * @param inputStream
     * @throws IOException
     */
    private void printKeyValue(InputStream inputStream) throws IOException {
        Properties properties = new Properties();
        properties.load(inputStream);
        Set<Object> keys = properties.keySet();
        for (Object key : keys) {
            System.out.println(key + " = " + properties.get(key));
        }
    }
}

总结

到此这篇关于Java读取properties配置文件的8种方式的文章就介绍到这了,更多相关Java读取properties配置文件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Java中的几种读取properties配置文件的方式

    相信对于一名JAVA开发者开说properties文件一定再熟悉不过了,比如一下配置: config.properties会经常存放一些系统常量,版本号,路径之类的 database.properties存放数据库的连接参数 log4j.properties 日志的一些基本配置 redis.properties 缓存数据库的一些配置 当然前缀是根据用能自行定义的,一般来说文件的内容的格式是"键=值"的格式,文本注释信息可以用"#"来注释,下面来说说开发中如何读写pr

  • Java读取.properties配置文件方法示例

    一.介绍 Properties文件在Java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值" 二.读取 这里我采用的是getResourceAsStream的文件读取方法 如果想要使用这个方法,则需要了解一些基本使用信息: 1.读取文件路径范围:只局限于工程的源文件中 2.文件访问形式:带"/"是绝对路径,不带"/"是相对路径 3.读取文件类型:主要为:.properties文件,.xml文件 三.使用

  • Java开发中读取XML与properties配置文件的方法

    相关阅读: 使用Ajax进行文件与其他参数的上传功能(java开发) 1. XML文件: 什么是XML?XML一般是指可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言. 2.XML文件的优点: 1)XML文档内容和结构完全分离. 2)互操作性强. 3)规范统一. 4)支持多种编码. 5)可扩展性强. 3.如何解析XML文档: XML在不同的语言中解析XML文档都是一样的,只不过实现的语法不一样,基本的解析方式有两种,一种是SAX方式,是按照XML文件的顺序一

  • Java读取properties配置文件时,出现中文乱码的解决方法

    如下所示: public static String getConfig(String key) { Properties pros = new Properties(); String value = ""; try { pros.load(new InputStreamReader(Object.class.getResourceAsStream("/properties.properties"), "UTF-8")); value = pr

  • Java读取.properties配置文件的几种方式

    Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易. 介绍几种读取方式: 1.基于ClassLoder读取配置文件 注意:该方式只能读取类路径下的配置文件,有局限但是如果配置文件在类路径下比较方便. Properties properties = new Properties(); // 使用ClassLoader加载propert

  • Java中使用Properties配置文件的简单方法

    properties Properties文件是java中的一种配置文件,文件后缀为".properties",文件的内容格式是"key=value"的格式,用 # 作为注释. 我的properties 文件放在路径 写与读 向properties文件中写入数据 //创建一个properties对象 Properties pro = new Properties(); //创建一个输出流 里面路径填写文件的路径 OutputStream proos = new Fi

  • java读取properties配置文件的方法

    本文实例讲述了java读取properties配置文件的方法.分享给大家供大家参考.具体分析如下: 这两天做java项目,用到属性文件,到网上查资料,好半天也没有找到一个满意的方法能让我读取到.properties文件中属性值,很是郁闷,网上讲的获取属性值大概有以下方法,以下三种方法逐渐优化,以达到最好的效果以下都以date.properties文件为例,该文件放在src目录下,文件内容为: startdate=2011-02-07 totalweek=25 方法一: public class

  • 详解Java程序读取properties配置文件的方法

    在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的.比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么IP ,数据库名称,表名称,数据库主机等信息是我们本地的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里.通常我们的做法是用配置文件来解决. 各种语言都有自己所支持的配置文件类型.比如Python ,他支持.ini 文件.因为他内部有一个ConfigParser 类来支持.ini 文件的读写,根据该类提供的方法程序员可以自由的来操作

  • java简单读取properties配置文件的方法示例

    本文实例讲述了java简单读取properties配置文件的方法.分享给大家供大家参考,具体如下: 读取配置文件,小结如下 import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class loadConf { private Properties prop = new Properties(); private void loadconf() t

  • Java读取properties配置文件的8种方式汇总

    目录 一.前言 二.Properties类 三.Properties常用方法实践 四.Java写入Properties 五.Java读取Properties 六.Properties配合Spring框架使用 七.完整代码 总结 一.前言 在做Java项目开发过程中,涉及到一些数据库服务连接配置.缓存服务器连接配置等,通常情况下我们会将这些不太变动的配置信息存储在以 .properties 结尾的配置文件中.当对应的服务器地址或者账号密码信息有所变动时,我们只需要修改一下配置文件中的信息即可.同时

  • Go语言读取YAML 配置文件的两种方式分享

    目录 前言 yaml.v3 包 读取 yaml 文件 viper 包 读取 yaml 文件 小结 前言 在日常开发中,YAML 格式的文件基本上被默认为是配置文件,其内容因为缩进带来的层级感看起来非常直观和整洁.本文将会对 YAML 内容的读取进行介绍. yaml.v3 包 yaml.v3 的包,可以让我们在 Go 里面轻松地操作 yaml 格式的数据(如将 yaml 格式转成结构体等).在使用 yaml.v3 包之前,我们需要先安装它: go get gopkg.in/yaml.v3 读取 y

  • Java读取Properties文件的七种方法的总结

    Java读取Properties文件的方法总结 读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法: 其实很多都是大同小异,概括起来就2种: 先构造出一个InputStream来,然后调用Properties#load() 利用ResourceBundle,这个主要在做国际化的时候用的比较多. 例如:它能根据系统语言环境自动读取下面三个properties文件中的一个: resource_en_US.properties resource_zh_CN.prop

  • 详解Spring-boot中读取config配置文件的两种方式

    了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息. Spring-Boot读取配置文件的方式: 一.读取核心配置文件信息application.properties的内容 核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单. 核心配置文件applicati

  • 详解Spring加载Properties配置文件的四种方式

    一.通过 context:property-placeholder 标签实现配置文件加载 1.用法示例: 在spring.xml配置文件中添加标签 复制代码 代码如下: <context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/> 2.在 spring.xml 中使用配置文件属性: <!-- 基本属性 url.

  • Spring加载properties文件的两种方式实例详解

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源代码,这样更加方便.在Spring中也可以这么做,而且Spring有两种加载properties文件的方式:基于xml方式和基于注解方式.下面分别讨论下这两种方式. 1. 通过xml方式加载properties文件 我们以Spring实例化dataSource为例,我们一般会在beans

随机推荐