Java属性配置Properties与XML

Love The Way You Lie 2024-01-20 08:06 109阅读 0赞

假设现在的属性配置以xml方式写入到properties.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
  3. <properties>
  4. <entry key="name">phil</entry>
  5. <entry key="id">1</entry>
  6. <entry key="password">123456</entry>
  7. </properties>

读配置:

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.PrintStream;
  4. import java.util.*;
  5. /**
  6. * 测试程序。
  7. */
  8. public class Main {
  9. public static void main(String[] args) {
  10. try {
  11. new Main().test();
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. private void test() throws Exception {
  17. printer();
  18. }
  19. private void printer() throws Exception {
  20. Properties prop = new Properties();
  21. FileInputStream fis = new FileInputStream("properties.xml");
  22. prop.loadFromXML(fis);
  23. fis.close();
  24. System.out.println("==========");
  25. Set<Map.Entry<Object, Object>> sets = prop.entrySet();
  26. Iterator<Map.Entry<Object, Object>> iterator = sets.iterator();
  27. while (iterator.hasNext()) {
  28. Map.Entry<Object, Object> entry = iterator.next();
  29. Object key = entry.getKey();
  30. Object value = entry.getValue();
  31. System.out.println(key + "->" + value + "-" + prop.getProperty(key.toString()));
  32. }
  33. }
  34. /**
  35. * 重新设置属性配置。
  36. *
  37. * @param key
  38. * @param value
  39. * @throws Exception
  40. */
  41. private void setProperty(String key, String value) throws Exception {
  42. Properties p = new Properties();
  43. p.setProperty("id", "2019");
  44. p.setProperty("password", "654321");
  45. PrintStream ps = new PrintStream(new File("test.properties"));
  46. p.storeToXML(ps, "set config");
  47. }
  48. }

输出:

  1. ==========
  2. password->123456-123456
  3. name->phil-phil
  4. id->1-1

发表评论

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

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

相关阅读