摘要:在java项目中经常会使用到配置文件,这里就介绍几种加载配置文件的方法。

本文分享自华为云社区《【Java】读取/加载 properties配置文件的几种方法》,作者:Copy工程师。

说明

在java项目中经常会使用到配置文件,这里就介绍几种加载配置文件的方法

目录结构

我是使用的maven搭建的项目,resources其实就是在根目录下
配置文件很简单

一、 基于ClassLoader读取配置文件

注意:有局限性只能在类路径下比较方便

Properties properties = new Properties();
// 注意这里的路径是根据根目录写的
InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties");
properties.load(in);
System.out.println("1111111111111---->:"+properties.getProperty("name")); 输出:
1111111111111---->:xing

二、基于InputStream读取配置文件

Properties properties2 = new Properties();
// 以下两种获取文件流的方式都可以,对于小文件第一种更快一点 // 通过BufferedReader获取文件流
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
properties2.load(bufferedReader);
System.out.println("22222222222---->:"+properties2.getProperty("name"));
}catch (Exception e){
e.printStackTrace();
}
// 通过FileInputStreamm获取文件流
InputStream in2 = new FileInputStream(new File(filePath));
properties2.load(in2);
System.out.println("22222222222---->:"+properties2.getProperty("name")); 输出:
22222222222---->:xing
22222222222---->:xing

三、基于ResourceBundle读取配置文件

// 1. 通过ResourceBundle.getBundle() 静态方法来获取文件 这种方式不需要添加后缀名
// 注意这里的ResourceBundle.getBundle("conf/demo") 这里不需要写配置文件的后缀 只需要名字即可 xml没试过 这里是properties
ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
System.out.println("333333333333----->:"+resourceBundle.getString("name"));
// 2. 通过InputStream读取文件
InputStream in3 = new FileInputStream(new File(filePath));
ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
System.out.println("333333333333----->:"+resourceBundle2.getString("name")); 输出:
333333333333----->:xing
333333333333----->:xing

四、基于PropertiesConfiguration读取配置文件 需要使用第三方的包

这是我推荐使用的方法,毕竟有大腿在,干嘛不去抱大腿,嘿嘿。我使用的包是commons-configuration2.x 。记住这是版本2 ,不是版本1, 2和1有很大的差别的。

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-configuration2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.2</version>
</dependency> try {
// 直接通过路径读取文件
Configurations configurations = new Configurations();
FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
//通过reader 读取文件 找了找好像没有通过InputStream读取文件的方式
PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
} catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
e.printStackTrace();
} 输出:
444444444444----->:xing
555555555555----->:xing

整个类:

package com.xing.test;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import java.io.*;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle; public class ReadProperties {
public static void main(String[] args) throws IOException {
String filePath = ReadProperties.class.getClassLoader().getResource("conf/demo.properties").getPath(); /** 方法一
* 基于ClassLoader读取配置文件
* 有局限性 只能在类路径下比较方便
*/
Properties properties = new Properties();
// 注意这里的路径是根据target/classes 的路径写的
InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties");
properties.load(in);
System.out.println("1111111111111---->:"+properties.getProperty("name"));
/** 方法二
* 基于InputStream读取配置文件
*
*/
Properties properties2 = new Properties();
// 两种获取文件流的方式都可以,对于小文件第一种更快一点
// 通过BufferedReader获取文件流
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
properties2.load(bufferedReader);
System.out.println("22222222222---->:"+properties2.getProperty("name"));
}catch (Exception e){
e.printStackTrace();
}
// 通过FileInputStreamm获取文件流
InputStream in2 = new FileInputStream(new File(filePath));
properties2.load(in2);
System.out.println("22222222222---->:"+properties2.getProperty("name"));
/** 方法三
* 基于ResourceBundle读取配置文件
*
*/
// 1. 通过ResourceBundle.getBundle() 静态方法来获取文件 这种方式不需要添加后缀名
ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
System.out.println("333333333333----->:"+resourceBundle.getString("name"));
// 2. 通过InputStream读取文件
InputStream in3 = new FileInputStream(new File(filePath));
ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
System.out.println("333333333333----->:"+resourceBundle2.getString("name"));
/** 方法四
* 基于PropertiesConfiguration读取配置文件 需要使用第三方的包
*
*/ try {
Configurations configurations = new Configurations();
FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
//InputStream in4 = new FileInputStream(new File(filePath));
PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
} catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
e.printStackTrace();
}
}
}

后记

通常在读取配置文件的时候都是写个工具类,在程序运行的时候就加载配置文件了。这里简单写了一个,凑合着看吧。

package com.xing.test;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PropertiesUtils { private static final Log log = LogFactory.getLog(PropertiesUtils.class); private static Configurations configurations = null;
private static PropertiesConfiguration propertiesConfiguration = null;
private static void initProperties(){
configurations = new Configurations();
FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
try {
propertiesConfiguration = configurations.properties(PropertiesUtils.class.getClassLoader().getResource("conf/demo.properties"));
} catch (ConfigurationException e) {
log.error("配置文件初始化失败",e);
}
}
static {
initProperties();
} /**
* 获取String类型的value
* @param key
* @return
*/
public static String getValueString(String key){
if (propertiesConfiguration == null){
initProperties();
}
return propertiesConfiguration.getString(key);
} /**
* 获取int类型的value
* @param key
* @return
*/
public static int getValueInt(String key){
if (propertiesConfiguration == null){
initProperties();
}
return propertiesConfiguration.getInt(key, 0);
} }

其实这个包还可以自动重载的功能,修改了配置文件不需要重启服务器即可加载重载配置文件。

点击关注,第一时间了解华为云新鲜技术~

你会几种读取/加载 properties配置文件方法的更多相关文章

  1. 加载Properties配置文件

    /** * 加载Properties配置文件 * * @author ZhangHaiNing * @param file 要读取的文件 * @return */ public static Prop ...

  2. Java加载Properties配置文件工具类

    Java加载Properties配置文件工具类 import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; ...

  3. 使用Spring加载properties配置文件.md

    背景 类似于datasource.properties之类的配置文件,最初通过Java的Properties类进行处理.这种方式有许多弊端,如每次都需要读取配置文件:若将Properties作为成员变 ...

  4. Spring加载Properties配置文件的三种方式

    一.通过 context:property-placeholder 标签实现配置文件加载 1) 用法: 1.在spring.xml配置文件中添加标签 <context:property-plac ...

  5. Java之JDBC 通过加载properties配置文件连接数据库

    通常情况下,我们通过JDBC连接数据库的时候,不会将数据库相关配置写死,因为到时候数据库一有改动,就要重新打包部署到服务器或者替换相关的.class文件,这样非常不灵活.因此,咱们一般会通过读取配置文 ...

  6. jquery和js的几种页面加载函数的方法以及执行顺序

    参考博客:http://www.cnblogs.com/itslives-com/p/4646790.html    https://www.cnblogs.com/james641/p/783837 ...

  7. spring加载properties配置文件

    public static void main(String[] args){    String path="E:/workspace/bocMarketData/src/config/P ...

  8. Spring加载properties文件的两种方式

    在项目中如果有些参数经常需要修改,或者后期可能需要修改,那我们最好把这些参数放到properties文件中,源代码中读取properties里面的配置,这样后期只需要改动properties文件即可, ...

  9. spring入门(二)【加载properties文件】

    在开发过程当中需要用到配置信息,这些信息不能进行硬编码,这时配置文件是一个比较好的方式,java提供了properties格式的文件,以键值对的方式保存信息,在读取的时候通过键获得键对应的值,spri ...

  10. JAVA加载Properties配置资源文件

    JAVA加载Properties配置资源文件 制作人:全心全意 配置文件(资源文件):以properties作为拓展名的文件 Java代码是如何加载properties文件的? 必须使用Propert ...

随机推荐

  1. HarmonyOS原生分析能力,即开即用助力精细化运营

    数据分析产品对开发者的价值呈现在两个层面,第一个是产品的层面,可以通过数据去洞察用户的行为,从而找到产品的优化点.另外一个就是运营层面,可以基于数据去驱动,来实现私域和公域的精细化运营. 在鸿蒙生态上 ...

  2. 监控Mysql数据库

    Prometheus(普罗米修斯) 监控Mysql数据库: 这个是基于第一版本环境搭建的,需要部署prometheus: 服务器 IP地址 Prometheus服务器 192.168.1.22 被监控 ...

  3. 20.1 OpenSSL 字符BASE64压缩算法

    OpenSSL 是一种开源的加密库,提供了一组用于加密和解密数据.验证数字证书以及实现各种安全协议的函数和工具.它可以用于创建和管理公钥和私钥.数字证书和其他安全凭据,还支持SSL/TLS.SSH.S ...

  4. Leetcode.456单调栈

    给你一个整数数组 nums ,数组中共有 n 个整数.132 模式的子序列 由三个整数 nums[i].nums[j] 和 nums[k] 组成,并同时满足:i < j < k 和 num ...

  5. C?C++?

    代码逆向 在这里需要注意的几个点: c#语言赋值号(=)右边的值同样会跟着左边的值改变,如array6=array2,array6+=2:这个时候array2也会变 如array7[num5] +=  ...

  6. 轻松一刻|Walrus CLI与CI/CD工具集成,轻松部署2048游戏

    Walrus 是一款开源的基于平台工程理念.以应用为中心.以完整应用系统自动化编排交付为目标进行设计开发的云原生应用平台,简化和自动化应用部署与发布流程并与现有的 CI/CD 流水线无缝集成.今天我们 ...

  7. (Good topic)快慢指针:链表的中间结点 (3.23leetcode每日打卡)

    给定一个带有头结点 head 的非空单链表,返回链表的中间结点. 如果有两个中间结点,则返回第二个中间结点.   示例 1: 输入:[1,2,3,4,5]输出:此列表中的结点 3 (序列化形式:[3, ...

  8. 【scipy 基础】--信号处理

    scipy.signal模块主要用于处理和分析信号.它提供了大量的函数和方法,用于滤波.卷积.傅里叶变换.噪声生成.周期检测.谱分析等信号处理任务. 此模块的主要作用是提供一套完整的信号处理工具,从而 ...

  9. Docker安装与教程-Centos7(一)

    复现漏洞时,经常要复现环境,VMware还原太过麻烦,所以学习docker的基本操作也是必要的 Docker三要素-镜像.容器.仓库 操作系统:Centos7 官方教程文档 1.Docker的安装与卸 ...

  10. 一套开源、强大且美观的WPF UI控件库 - HandyControl

    前言 今天给大家推荐一套开源.强大且美观的WPF UI控件库:HandyControl. WPF介绍 WPF 是一个强大的桌面应用程序框架,用于构建具有丰富用户界面的 Windows 应用.它提供了灵 ...