读取Config文件工具类 PropertiesConfig.java

时间:2023-03-09 07:55:47
读取Config文件工具类 PropertiesConfig.java
  1. package com.util;
  2. import java.io.BufferedInputStream;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.util.Properties;
  6. /**
  7. * 读取Config文件工具类
  8. * @version 1.0
  9. * @since JDK 1.6
  10. */
  11. public class PropertiesConfig {
  12. /**
  13. * 获取整个配置文件中的属性
  14. * @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties
  15. */
  16. public static Properties readData(String filePath) {
  17. filePath = getRealPath(filePath);
  18. Properties props = new Properties();
  19. try {
  20. InputStream in = new BufferedInputStream(new FileInputStream(filePath));
  21. props.load(in);
  22. in.close();
  23. return props;
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. return null;
  27. }
  28. }
  29. private static String getRealPath(String filePath) {
  30. //获取绝对路径 并截掉路径的”file:/“前缀
  31. return PropertiesConfig.class.getResource("/" + filePath).toString().substring(6);
  32. }
  33. }