zoukankan      html  css  js  c++  java
  • java学习-加载.properties工具类

    javaWeb项目,要加载xxx.properties或其它如.txt, .md后缀的文本文件

    文本内容有两种格式

    key:value或者key=value

    诸如Spring框架,Jfinal框架,都是使用java.util.Properties类来加载文本配置文件

    Poperties类是按行读取key和value,所以我们写配置文件时,只能一行一个key/value键值对

    这些配置文件一般会在编译时打包到WEB-INF/classes/文件夹下

    我们要加载时就要通过使用下面方法获取InputStream输入流

    class.getResourceAsStream(String name)
    最后调用Properties.load(InputStream)就可以通过Properties.getProperty(key)获得对应值
    具体实例
    注意,我们设置资源文件是src/main/resources,,而mapper没有设置为资源文件
    /src/main/resources/mapper/jdbc.properties
    # set up mysql driver
    # may need auto detect this driver class
    jdbc.driver:com.mysql.jdbc.Driver
    jdbc.url:jdbc:mysql://localhost:3306/ssm?useUnicode=true&useSSL=false&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=root

    原生读取配置文件

     1         ClassLoader ret = Thread.currentThread().getContextClassLoader();
     2         if(ret==null) {
     3             ret=ClassLoader.getSystemClassLoader();
     4         }
     5         
     6         InputStream inputStream = ret.getResourceAsStream("mapper/jdbc.properties");
     7         Properties properties=new Properties();
     8         try {
     9             properties.load(inputStream);
    10         } catch (IOException e) {
    11             e.printStackTrace();
    12         }
    13         finally {
    14             if (inputStream != null)
    15                 try {
    16                     inputStream.close();
    17                 } catch (IOException e) {
    18                     e.printStackTrace();;
    19                 }
    20         }
    21         
    22         System.out.println(properties.getProperty("jdbc.password"));

    结果
    root

    用这种方式读取配置文件有个问题,那就是如果文件使用utf-8编码,而我们windows电脑默认用ISO-8859-1编码,如果读取中文,会发生乱码

    在这里spring和jfinal读取配置文件工具类做的优化,会将inputStream转换成new InputStreamReader(inputStream,"UTF-8")使用utf-8编码的字符流读取配置文件,

    这样就不会有乱码问题。

    改进如下

    将第9行的代码替换

    properties.load(new InputStreamReader(inputStream, "UTF-8"));

    这样读取含有中文的值时,就不会发生报错的

    spring读取配置文件的方法

    方法1

    只是借助ResourceLoader类获得具体的资源文件,classpath表示资源文件是在WEB-INF/classes/下,才底层自动决定用哪种方式加载

    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.Properties;
    import org.springframework.core.io.DefaultResourceLoader;
    import org.springframework.core.io.Resource;
    
    Resource resource = new DefaultResourceLoader().getResource("classpath:/mapper/jdbc.properties");
            Properties properties1 = new Properties();
            try {
                properties1.load(new InputStreamReader(resource.getInputStream(), "UTF-8"));
                System.out.println(properties1.getProperty("jdbc.password"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

    方法2

    直接使用class资源加载类,然后调用PropertiesUtils工具类获得Propertiesg类,

    这个工具类还可以加载xml文件

    import java.io.IOException;
    import java.util.Properties;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.support.EncodedResource;
    import org.springframework.core.io.support.PropertiesLoaderUtils;
    
    Resource res = new ClassPathResource("mapper/jdbc.properties");
            try {
                System.out.println(res.getFile().getAbsolutePath());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            
            EncodedResource encRes = new EncodedResource(res,"UTF-8");
            try {
                Properties properties = PropertiesLoaderUtils.loadProperties(encRes);
                String jdbc=properties.getProperty("jdbc.password");
                System.out.println(jdbc);
            } catch (IOException e) {
                e.printStackTrace();
            }

    结果

    D:WorkSpacesSSMTest argetclassesmapperjdbc.properties
    root

    Jfinal框架是使用PropKit工具类一次加载properties文件后,可以在程序的任何地方使用它

     底层实现都是相同的,

    加载WEB-INF/classes/目录下的资源文件

    import com.jfinal.kit.PropKit;
    
            PropKit.use("config-local.txt");
            System.out.println(PropKit.get("devMode"));
            
            PropKit.use("log4j.properties");
            System.out.println(PropKit.getProp("log4j.properties").get("log4j.rootLogger"));
            
            System.out.println(PropKit.get("devMode"));
            System.exit(0);

    有两种情况:

    如果只有一个配置文件

    默认使用PropKit.get(Key)就可以获得value值

    如果有多个配置文件,

    要获取对应文件的key值

    必须使用

    PropKit.getProp(fileName).get(Key),获取以文件名为key的Prop对象来获取对应的值,

    如果还是使用PropKit.get(Key),只保存的第一次调用PropKit.use(FileName)的属性值

    这个PropKit内部使用ConcurrentHashMap存放多个配置文件的属性

    即使所有操作都是线程安全的,检索操作也不需要锁定,并且没有任何支持以阻止所有访问的方式锁定整个表

    适用于高并发环境

    private static final ConcurrentHashMap<String, Prop> map = new ConcurrentHashMap<String, Prop>();
  • 相关阅读:
    学习淘宝指数有感
    STL学习小结
    Java里泛型有什么作用
    android 内存泄漏分析技巧
    学道1.3
    严苛模式(StrictMode)
    年龄大了还能够学习编程吗
    ORACLE EXP命令
    数学之路-python计算实战(13)-机器视觉-图像增强
    《C语言编写 学生成绩管理系统》
  • 原文地址:https://www.cnblogs.com/gne-hwz/p/10191540.html
Copyright © 2011-2022 走看看