• 【Java】Properties文件的解析


     1 public abstract class ReadProperties {
     2 
     3     public ReadProperties() {}
     4     
     5     /**
     6      * 回调函数,由调用者处理
     7      * @param key
     8      * @param value
     9      */
    10     public abstract void dealKeyAndValue(String key, String value);
    11     
    12     /**
    13      * 根据包路径解析
    14      * @param packagePath
    15      * @throws IOException
    16      */
    17     public void read(String packagePath) throws IOException {
    18         InputStream is = this.getClass().getResourceAsStream(packagePath);
    19         read(is);
    20     }
    21     
    22     /**
    23      * 根据文件的绝对路径解析
    24      * @param absolutePath
    25      * @throws IOException
    26      */
    27     public void readFile(String absolutePath) throws IOException {
    28         read(new File(absolutePath));
    29     }
    30     
    31     /**
    32      * 根据{@link File}解析
    33      * @param file
    34      * @throws IOException
    35      */
    36     public void read(File file) throws IOException {
    37         read(new FileInputStream(file));
    38     }
    39     
    40     /**
    41      * 根据{@link InputStream}解析
    42      * @param is
    43      * @throws IOException
    44      */
    45     public void read(InputStream is) throws IOException {
    46         Properties properties = new Properties();
    47         try {
    48             // Properties文件会出现乱码问题,以UTF-8的方式打开
    49             properties.load(new InputStreamReader(is, "UTF-8"));
    50             Enumeration<Object> keys = properties.keys();
    51             
    52             while (keys.hasMoreElements()) {
    53                 String key = (String) keys.nextElement();
    54                 String value = properties.getProperty(key);
    55                 properties.get(key);
    56                 
    57                 dealKeyAndValue(key, value);
    58             }
    59         } finally {
    60             is.close();
    61         }
    62     }
    63         
    64 }

    使用:
    在src下新建一个test.properties文件如下:

    执行解析:

     1 public class Test {
     2 
     3     public static void main(String[] args) throws Exception {
     4         new ReadProperties() {
     5             @Override
     6             public void dealKeyAndValue(String key, String value) {
     7                 System.out.println(key + " = " + value);
     8             }
     9         }.read("/test.properties");;
    10     }
    11 
    12 }

    结果如下:

  • 相关阅读:
    IOS的系统手机 宽度无法自适应 解决办法
    iframe 设置背景透明
    thinkphp5 常用的2个方法
    thinkphp引入后台模板文件的路径怎么写?
    html的confirm()
    php 如何往数组里添加数据
    thinkphp51 重定向 redirect()
    【Oracle 触发器】(4)触发器应用场景--数据的确认
    【Oracle 触发器】(3)触发器应用场景--复杂的安全性检查
    【Oracle 触发器】(2)触发器的分类(语句级/行级)
  • 原文地址:https://www.cnblogs.com/a526583280/p/10725026.html
Copyright © 2020-2023  润新知