一、什么是properties文件?
properties文件是相当于map的k-v键值对文件。 代表的类对象有new Properties();
driver-class-name=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/springdatajpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghaiusername=rootpassword=123456
二、使用场景?
目前遇到的好比是配置mysqljdbc连接
知识要点
- 用到Properties类的load()方法
- load()方法需要流参数
- 需要读取文件,而后使用load()方法加载
代码示例
package com.jpa.common.properties;import java.io.*;import java.util.Properties;import java.util.Set;/*** @author OVAmach* @date 2021/5/24*/public class PropertiesUtils {/*** 单独抽取的方法,用户检测能否正确操纵Properties** @param inputStream* @throws IOException 为了排版美观,直接抛出异常*/public static void printKeyValue(InputStream inputStream) throws IOException {Properties properties = new Properties();//使用properties加载出来文件properties.load(inputStream);Set<Object> keys = properties.keySet();for (Object key : keys) {System.out.println(key + " = " + properties.get(key));}}/**** 从当前的类加载器的getResourcesAsStream来获取.* 使用Class.class.getClassLoader().getResourcesAsStream()进行获取的时候,所填写的路径只能为项目的绝对路径* @throws IOException** getResourceAsStream()从当前项目的resource目录下加载配置文件*/public static void getPropertiesFromResourceAsStream() throws IOException {InputStream resourceAsStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("properties/jdbc.properties");printKeyValue(resourceAsStream);}/**** 从文件中获取,使用InputStream字节* 主要是需要加上src这个文件夹名。。。路径配置需要精确到绝对地址级别* 什么意思,就是如果这个mylog4j文件在com/dimple/getproperityfile/mylog4j.properties下,而这个com文件夹* 又在src目录下,那么写的时候需要加上这个src,这样的相对路径+项目地址能够构成一个完整的访问地址即可* @throws IOException*/public static void getPropertiesFromFile() throws IOException {InputStream inputStream = new FileInputStream(new File("src/main/resources/properties/jdbc.properties"));printKeyValue(inputStream);}/*** 使用Class类的getSystemResourceAsStream方法* 和使用当前类的ClassLoader是一样的* 加载当前resource目录下的文件* @throws IOException*/public static void getPropertiesFromClassLoader() throws IOException {InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("properties/jdbc.properties");printKeyValue(systemResourceAsStream);}public static void main(String[] args) throws IOException {// File file = new File("E:\\spring-data-jpa\\gittest-master\\jpa-01\\src\\main\\resources\\properties\\jdbc.properties");// getPropertiesFromClassLoader();// getPropertiesFromFile();getPropertiesFromResourceAsStream();}}
