Java 读取 .properties 配置文件的几种方式 及.properties文件的内容格式

Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中。然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配置文件就比较容易。

properties 文件内容格式:

在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么IP ,数据库名称,表名称,数据库主机等信息是我们本地的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里。通常我们的做法是用配置文件来解决。

在Java中,其配置文件常为.properties文件,格式为文本文件,JDK 内置的java.util.Properties 类 支持.properties 文件的读写,为我们操作 .properties 文件提供了便利。

设数据如下:

#以下为服务器、数据库信息
dbPort = localhost
databaseName = mydb
dbUserName = root
dbPassword = root
#以下为数据库表信息
dbTable = mytable
#以下为服务器信息
ip = 192.168.0.9

在配置文件db.properties 中,其中# 开始的一行为注释信息;在等号“= ”左边的我们称之为key等号“= ”右边的我们称之为value 。(其实就是我们常说的键- 值对)key 应该是我们程序中的变量。而value 是我们根据实际情况配置的。

二 Java中Properties类的操作

ava中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。Properties类提供了几个主要的方法:

1 load( InputStream inStream )

这个方法可以从 .properties属性文件 对应的文件输入流中,加载属性列表到Properties类对象,即通过对上面的 properties 文件进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

Properties pro = new Properties();
FileInputStream in = new FileInputStream("ab.properties");
pro.load(in);
in.close();

2 getProperty ( String key )
获取属性信息
即用指定的键在属性列表中搜索属性 也就是通过参数 key 得到 key 所对应的 value。

 

Properties pro = new Properties();
FileInputStream in = new FileInputStream("ab.properties");
pro.load(in);
String value = pro.getProperty(key);//根据key获取内容
in.close();

3 setProperty ( String key, String value )
设置属性信息
即通过调用基类的put方法来设置 键 - 值对。

4 store( OutputStream out, String comments )
这个方法将Properties类对象的属性列表保存到输出流中
即与 load 方法相反,该方法将键 - 值对写入到指定的文件中去

FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close();

 

Java读取Properties文件

Java读取Properties文件的方法有很多,但是最常用的还是通过java.lang.Class类 getResourceAsStream(String name)方法来实现,如下可以这样调用:

InputStream in = getClass().getResourceAsStream("资源Name");

但是也可以使用InputStream抽象类中的FileInputStream实现类进行读取。

InputStream in= new BufferedInputStream(new FileInputStream(filePath));

根据key读取value
读取properties的全部信息
写入新的properties信息

//关于Properties类常用的操作
public class TestProperties {
    //根据Key读取Value
    public static String GetValueByKey(String filePath, String key) {
        Properties pps = new Properties();
        try {
            InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
            pps.load(in);
            String value = pps.getProperty(key);
            System.out.println(key + " = " + value);
            return value;
            
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //读取Properties的全部信息
    public static void GetAllProperties(String filePath) throws IOException {
        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        Enumeration en = pps.propertyNames(); //得到配置文件的名字
        
        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
        
    }
    
    //写入Properties信息
    public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
        Properties pps = new Properties();
        
        InputStream in = new FileInputStream(filePath);
        //从输入流中读取属性列表(键和元素对) 
        pps.load(in);
        //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。  
        //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream out = new FileOutputStream(filePath);
        pps.setProperty(pKey, pValue);
        //以适合使用 load 方法加载到 Properties 表中的格式,  
        //将此 Properties 表中的属性列表(键和元素对)写入输出流  
        pps.store(out, "Update " + pKey + " name");
    }
    
    public static void main(String [] args) throws IOException{
        //String value = GetValueByKey("db.properties", "name");
        //System.out.println(value);
        //GetAllProperties("db.properties");
        WriteProperties("db.properties","long", "212");
    }
}

运行main函数得到:

 

#Update long name
#Sun Feb 23 18:17:16 CST 2014
name=JJ
Weight=4444
long=212
Height=3333

 从上面的的例子当中可以知道 当系统配置文件数量过大时候,需要单独写一个读取配置文件的类。然后在Main函数或者其他可运行方法中执行(通过上面的例子不难看出,在Java中操作配置文件是非常简单的。在一个需要用到大量配置信息的模块或系统里,我们有必要封装一个专门的类来共使用。通过最后的main函数调用。)

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot读取application.properties的值的方式有多种方法。一种常用的方式是通过使用@Value注解来注入属性值。可以在需要使用属性值的字段、方法的参数、方法的返回值上添加@Value注解,并指定要注入的属性的键名。例如,可以使用@Value("${spring.rabbitmq.host}")来注入application.properties文件中的spring.rabbitmq.host属性的值。这样,在程序运行时,Spring Boot会自动读取属性文件中的值,并将其注入到相应的位置。 另一种方式是使用PropertiesLoaderUtils类来读取属性文件的值。首先,需要导入java.util.Properties和org.springframework.core.io.support.PropertiesLoaderUtils类。然后,可以使用PropertiesLoaderUtils的loadProperties方法来加载属性文件,然后使用getProperty方法获取具体的属性值。例如,可以使用Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("application.properties"))来加载application.properties文件,然后使用properties.getProperty("spring.rabbitmq.host")来获取spring.rabbitmq.host属性的值。 总结起来,Spring Boot提供了多种方式读取application.properties文件的值,可以根据具体的需求选择适合的方式来获取属性值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring Boot中配置文件application.properties使用](https://download.csdn.net/download/weixin_38672800/12765190)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringBoot获得application.properties中数据的几种方式](https://blog.csdn.net/m0_67393686/article/details/124421983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringBoot读取application.properties配置文件](https://blog.csdn.net/watson2017/article/details/124732267)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值