加载properties文件的方法

一、什么是properties文件?

properties文件是相当于map的k-v键值对文件。 代表的类对象有new Properties();

  1. driver-class-name=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/springdatajpa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
  3. username=root
  4. password=123456

二、使用场景?

目前遇到的好比是配置mysqljdbc连接

知识要点

  1. 用到Properties类的load()方法
  2. load()方法需要流参数
  3. 需要读取文件,而后使用load()方法加载

代码示例

  1. package com.jpa.common.properties;
  2. import java.io.*;
  3. import java.util.Properties;
  4. import java.util.Set;
  5. /**
  6. * @author OVAmach
  7. * @date 2021/5/24
  8. */
  9. public class PropertiesUtils {
  10. /**
  11. * 单独抽取的方法,用户检测能否正确操纵Properties
  12. *
  13. * @param inputStream
  14. * @throws IOException 为了排版美观,直接抛出异常
  15. */
  16. public static void printKeyValue(InputStream inputStream) throws IOException {
  17. Properties properties = new Properties();
  18. //使用properties加载出来文件
  19. properties.load(inputStream);
  20. Set<Object> keys = properties.keySet();
  21. for (Object key : keys) {
  22. System.out.println(key + " = " + properties.get(key));
  23. }
  24. }
  25. /***
  26. * 从当前的类加载器的getResourcesAsStream来获取.
  27. * 使用Class.class.getClassLoader().getResourcesAsStream()进行获取的时候,所填写的路径只能为项目的绝对路径
  28. * @throws IOException
  29. *
  30. * getResourceAsStream()从当前项目的resource目录下加载配置文件
  31. */
  32. public static void getPropertiesFromResourceAsStream() throws IOException {
  33. InputStream resourceAsStream = PropertiesUtils.class.getClassLoader().getResourceAsStream("properties/jdbc.properties");
  34. printKeyValue(resourceAsStream);
  35. }
  36. /***
  37. * 从文件中获取,使用InputStream字节
  38. * 主要是需要加上src这个文件夹名。。。路径配置需要精确到绝对地址级别
  39. * 什么意思,就是如果这个mylog4j文件在com/dimple/getproperityfile/mylog4j.properties下,而这个com文件夹
  40. * 又在src目录下,那么写的时候需要加上这个src,这样的相对路径+项目地址能够构成一个完整的访问地址即可
  41. * @throws IOException
  42. */
  43. public static void getPropertiesFromFile() throws IOException {
  44. InputStream inputStream = new FileInputStream(new File("src/main/resources/properties/jdbc.properties"));
  45. printKeyValue(inputStream);
  46. }
  47. /**
  48. * 使用Class类的getSystemResourceAsStream方法
  49. * 和使用当前类的ClassLoader是一样的
  50. * 加载当前resource目录下的文件
  51. * @throws IOException
  52. */
  53. public static void getPropertiesFromClassLoader() throws IOException {
  54. InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("properties/jdbc.properties");
  55. printKeyValue(systemResourceAsStream);
  56. }
  57. public static void main(String[] args) throws IOException {
  58. // File file = new File("E:\\spring-data-jpa\\gittest-master\\jpa-01\\src\\main\\resources\\properties\\jdbc.properties");
  59. // getPropertiesFromClassLoader();
  60. // getPropertiesFromFile();
  61. getPropertiesFromResourceAsStream();
  62. }
  63. }