Java属性配置Properties

约定不等于承诺〃 2023-10-18 19:38 253阅读 0赞

简单的属性配置,比如一个配置文件test.properties内容:

  1. password=123456
  2. id=1
  3. name=phil

读取配置:

  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("test.properties");
  22. prop.load(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. */
  40. private void setProperty(String key, String value) throws Exception {
  41. Properties p = new Properties();
  42. p.setProperty("id", "2019");
  43. p.setProperty("password", "654321");
  44. PrintStream ps = new PrintStream(new File("test.properties"));
  45. p.list(ps);
  46. }
  47. }

输出:

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

发表评论

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

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

相关阅读

    相关 Properties配置属性文件步骤

    要求: 在平时的代码编写中,我们有一些常量是不需要改变并且会经常使用到的,我们可以把它配置到属性文件中,这样就方便后面的修改与维护。 方法: 第一步:可以选择在工程

    相关 java 属性(Properties)类

    属性继承于Hashtable中,表示一个持久的属性集。属性列表中每个键及其对应值都是一个字符串 属性定义如下实例变量。这个变量持有一个属性对象相关的默认属性列表 属