java 获取配置文件中的属性值

╰+哭是因爲堅強的太久メ 2024-01-18 06:19 78阅读 0赞

java web 应用,很多场景需要用到配置文件中的各个属性值。java Properties 类可以实现这类功能。源码如下所示。

  1. package *****.utils;
  2. import org.apache.commons.lang.exception.ExceptionUtils;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.*;
  6. import java.util.Properties;
  7. /**
  8. * @description
  9. * @date 2018/7/11 17:22
  10. */
  11. public class PropertyUtil {
  12. private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
  13. /**
  14. * 从指定配置文件获取指定属性值
  15. * @param path 文件路径,如:D://testConfig.properties
  16. * @param key 属性,如:testLock
  17. * @return testLock 的属性值
  18. */
  19. public static String getProperties(String path, String key) {
  20. Properties prop = new Properties();
  21. InputStream in = null;
  22. String value = null;
  23. try {
  24. // 通过输入缓冲流进行读取配置文件
  25. in = new BufferedInputStream(new FileInputStream(new File(path)));
  26. // 加载输入流
  27. prop.load(in);
  28. // 根据关键字获取value值
  29. value = prop.getProperty(key);
  30. } catch (Exception e) {
  31. logger.error(ExceptionUtils.getFullStackTrace(e));
  32. } finally {
  33. if (in != null) {
  34. try {
  35. in.close();
  36. } catch (IOException e1) {
  37. logger.error(ExceptionUtils.getFullStackTrace(e1));
  38. }
  39. }
  40. }
  41. return value;
  42. }
  43. }

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读