Java工具类--读取Properties文件

女爷i 2022-05-10 06:16 387阅读 0赞
  1. package com.skr.mdm.util;
  2. import net.sf.json.JSONArray;
  3. import net.sf.json.JSONObject;
  4. import java.io.InputStreamReader;
  5. import java.util.*;
  6. /**
  7. * 读取配置文件的工具类
  8. */
  9. public class PropertiesUtil {
  10. private Properties props;
  11. public PropertiesUtil(String fileName) {
  12. readProperties(fileName);
  13. }
  14. /**
  15. * 加载配置文件
  16. *
  17. * @param fileName
  18. */
  19. private void readProperties(String fileName) {
  20. try {
  21. props = new Properties();
  22. InputStreamReader inputStream = new InputStreamReader(
  23. this.getClass().getClassLoader().getResourceAsStream(fileName), "UTF-8");
  24. props.load(inputStream);
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. /**
  30. * 根据key读取对应的value
  31. *
  32. * @param key
  33. * @return
  34. */
  35. public String get(String key) {
  36. return props.getProperty(key);
  37. }
  38. /**
  39. * 得到所有的配置信息
  40. *
  41. * @return
  42. */
  43. public Map<String, String> getAll() {
  44. Map<String, String> map = new HashMap<String, String>();
  45. Enumeration<?> enu = props.propertyNames();
  46. while (enu.hasMoreElements()) {
  47. String key = (String) enu.nextElement();
  48. String value = props.getProperty(key);
  49. map.put(key, value);
  50. }
  51. return map;
  52. }
  53. /**
  54. * 得到所有的配置信息
  55. *
  56. * @return
  57. */
  58. public List<String> keyList() {
  59. List<String> keyList = new ArrayList<>() ;
  60. Enumeration<?> enu = props.propertyNames();
  61. while (enu.hasMoreElements())
  62. keyList.add((String) enu.nextElement()) ;
  63. return keyList;
  64. }
  65. public static void main(String[] args) {
  66. PropertiesUtil propertiesUtil = new PropertiesUtil("MDMTag.properties") ;
  67. System.out.println(JSONObject.fromObject(propertiesUtil.getAll())) ;
  68. System.out.println(JSONArray.fromObject(propertiesUtil.keyList())) ;
  69. }
  70. }

转至:https://blog.csdn.net/frankcheng5143/article/details/50432820?locationNum=10

发表评论

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

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

相关阅读