zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JAVA魔法堂:读取.properties配置文件

JAVA配置文件 读取 properties 魔法
2023-09-14 08:57:59 时间

一、前言

  Java工程中想log4j、数据库连接等配置信息一般都写在.properties文件中,那么如何读取这些配置信息呢?下面把相关方法记录下来供以后查阅。

 

二、.properties文件

  配置文件的一种,内容以键值对的形式存在,且每个键值对独占一行。#号作为行注释的起始标志,中文注释会自动进行unicode编码。示例:


# ip and port of server socket

ip=127.0.0.1

port=9999

# error message

msg=Im sorry, bye bye!

 假设上述内容存储在config.properties文件下,且bin目录结果如下:

  bin

    |-- main

        |-- Demo.class

    |-- config.properties

   后续章节的示例将以上述内容作为目标对象来操作。

三、通过 Properties对象 操作  

  读取属性,示例:

public class Demo{

 public static void main(String[] args){

 Properties props = new Properties();

 InputStream in = Demo.class.getResourceAsStream("../config.properties");

 // 或使用文件输入流(不推荐),假设当前工作目录为bin

 //InputStream in = new FileInputStream("./config.properties");

 props.load(in);

 in.close();

 // 读取特定属性

 String key = "ip";

 String ip = props.getProperty(key);

 // 遍历所有属性,方式一

 Set keys = props.keySet();

 for (Interator it = keys.iterator(); it.hasNext();){

 String k = it.next();

 System.out.println(k + ":" + props.getProperty(k));

 // 遍历所有属性,方式二

 Enumeration en = props.propertyNames();

 while (en.hasMoreElements()){

 String k = en.nextElement();

 System.out.println(k + ":" + props.getProperty(k));

}

 1. 通过 Demo.class.getResourceAsStream("../config.properties"); 读取配置文件,配置文件的相对路径以类文件所在目录作为当前目录。

   2. 通过 new FileInputStream("./config.properties"); 读取配置文件,配置文件的相对路径以工作目录(可以通过 System.getProperty("user.dir") 获取工作目录)作为当前目录。

   注意:上述两种方式获取的配置文件均没有被缓存。每次都要重新加载配置文件。


Properties props = new Properties();

InputStream in = getClass().getResouceAsStream("properties文件相对于当前类加载路径的文件目录");

props.load(in);

OutputStream output = new FileOutputStream("properties文件路径");

props.setProperty("ip", "10.248.112.123"); // 修改或新增属性键值对

props.store(output, "modify ip value"); // store(OutputStream output, String comment)将修改结果写入输出流

output.close()

四、通过 ResourceBundle对象 操作

  通过该方式仅能读取配置文件而已,不能进行写操作。示例:

// ResourceBundle rb = ResourceBundle.getBundle("配置文件相对工程根目录的相对路径(不含扩展名)");

ResourceBundle rb = ResourceBundle.getBundle("config");

 String name = rb.getString("name");

catch(MissingResourceException ex){

注意:上述方式会缓存配置文件信息,后续读取时均是读取缓存中的内容,若在此期间修改了配置内容是无法实时同步的

ResourceBundle有两个子类ListResourceBundle和PropertyResourceBundle,在读取properties文件时实际上是使用PropertyResourceBundle来处理。

题外话:

  ResourceBundle主要用于解决国际化和本地化问题。通过资源命名定义各语言和方言的信息,然乎程序在运行时获取当前本地化信息,并根据本地化信息加载相应的资源完成本地化。


// 含家族名、语言和国家 MyResource_en_US  对应的Java代码:
// ResourceBundle首先会根据语言和国家的本地化信息去查找资源(假设现在要查找MyResource_zh_CN),当找不到时就会找MyResource_zh,再找不到就用MyResource。

ResourceBundle rb = ResourceBundle.getBundle("MyResource", Locale.getDefault())

五、总结

  当然方式不止这些啦,日后继续补充!


Java工程中读取resources目录下properties文件的几种方法 本文主要介绍了几种读取工程resources目录下properties文件的方法以及注意事项,实际开发中可以根据自己的需要选择合适的方式。