ConfigLoader.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.mes.util;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.Properties;
  9. public class ConfigLoader {
  10. private static final String CONFIG_PATH = "config/config.properties";
  11. public static InputStream openConfigStream() throws IOException {
  12. ClassLoader cl = ConfigLoader.class.getClassLoader();
  13. InputStream is = cl != null ? cl.getResourceAsStream(CONFIG_PATH) : null;
  14. if (is == null) {
  15. is = ConfigLoader.class.getResourceAsStream("/" + CONFIG_PATH);
  16. }
  17. if (is == null) {
  18. File[] candidates = new File[]{
  19. new File("src/resources/" + CONFIG_PATH),
  20. new File(CONFIG_PATH),
  21. new File("bin/" + CONFIG_PATH)
  22. };
  23. for (File file : candidates) {
  24. if (file.isFile()) {
  25. return new FileInputStream(file);
  26. }
  27. }
  28. }
  29. if (is == null) {
  30. throw new IOException("找不到配置文件: " + CONFIG_PATH);
  31. }
  32. return is;
  33. }
  34. public static Properties loadProperties() throws IOException {
  35. Properties pro = new Properties();
  36. try (InputStream is = openConfigStream();
  37. BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
  38. pro.load(br);
  39. }
  40. return pro;
  41. }
  42. }