PropertiesUtil.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.template.common.utils;
  2. import java.io.*;
  3. import java.net.URI;
  4. import java.util.Enumeration;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import java.util.Properties;
  8. /**
  9. * <p>Title: PropertiesUtil</p>
  10. * <p>Description: properties资源文件解析工具</p>
  11. * @author fengyong
  12. * @date 2018年9月7日
  13. */
  14. public class PropertiesUtil {
  15. private static Properties props = null;
  16. private static URI uri;
  17. private static String fileName = "/application.properties";
  18. private static InputStream in = null;
  19. static {
  20. try {
  21. props = new Properties();
  22. InputStream fis = PropertiesUtil.class.getResourceAsStream(fileName);
  23. props.load(fis);
  24. uri = PropertiesUtil.class.getResource(fileName).toURI();
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. /**
  30. * 获取某个属性
  31. */
  32. public static String getProperty(String key) {
  33. try {
  34. props.load(PropertiesUtil.class.getResourceAsStream(fileName));
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. return props.getProperty(key);
  39. }
  40. /**
  41. * 获取所有属性,返回一个map,不常用 可以试试props.putAll(t)
  42. */
  43. @SuppressWarnings("rawtypes")
  44. public static Map<String, String> getAllProperty() {
  45. Map<String, String> map = new HashMap<String, String>();
  46. Enumeration enu = props.propertyNames();
  47. while (enu.hasMoreElements()) {
  48. String key = (String) enu.nextElement();
  49. String value = props.getProperty(key);
  50. map.put(key, value);
  51. }
  52. return map;
  53. }
  54. /**
  55. * 在控制台上打印出所有属性,调试时用。
  56. */
  57. public static void printProperties() {
  58. props.list(System.out);
  59. }
  60. /**
  61. * 写入properties信息
  62. */
  63. public static void writeProperties(String key, String value) {
  64. try {
  65. OutputStream fos = new FileOutputStream(new File(uri));
  66. props.setProperty(key, value);
  67. // 将此 Properties 表中的属性列表(键和元素对)写入输出流
  68. props.store(fos, "『comments』Update key:" + key);
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. /**
  74. * 取默认key的value
  75. * */
  76. public static String getValue(String key){
  77. String value = null;
  78. props = new Properties();
  79. in = PropertiesUtil.class.getResourceAsStream(fileName);
  80. try {
  81. props.load(in);
  82. } catch (IOException e) {
  83. // e.printStackTrace();
  84. }
  85. value = (String) props.get(key);
  86. return value;
  87. }
  88. }