Properties类读取配置文件

Properties类读取配置文件

一、前言

代码开发中如果需要读取配置文件信息,java自带的Properties类就是一个操作配置文件操作非常简单的类。下面介绍Properties两个方面,分别是如何加载配置文件信息和Properties提供的常用方法。

二、Properties加载文件两种方式

Properties第一种方式加载配置文件

  1. 实例化 Properties 类对象:Properties prop = new Properties();
  2. 对象调用load方法,传入字节流类型参数。
public class ProperTest {
    /**
     * Properties 类加载配置文件信息
     */
    public static void main(String[] args) {

        try {
            // 1.实例化 Properties类对象
            Properties prop = new Properties();

            /**
             * 2.通过对象调用load方法读取配置文件。
             *  2.1 load方法参数是字节流类型,所以需要创建一个字节流对象。
             *  2.2 将字节流对象传递给 load方法,加载文件信息。
             */

            File file = new File("src/main/resources/prop.properties");
            InputStream fileInputStream = new FileInputStream(file);
            prop.load(fileInputStream);

            //输出配置文件信息
            String propName = prop.getProperty("IAccountService");
            System.out.println(propName);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
发布了316 篇原创文章 · 获赞 117 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/m0_38039437/article/details/104933925