读取proerties文件

一.java读取properties

1、基于ClassLoader

ClassLoader类的getResource(String name),getResourceAsStream(String name)等方法,使用相对于当前项目的classpath的相对路径来查找资源。

  1. Thread.currentThread().getContextClassLoader().getResource("")
    得到的也是当前ClassPath的绝对URI路径。

  2. FileTest.class.getClassLoader().getResource("")
    得到的也是当前ClassPath的绝对URI路径。

推荐使用
Thread.currentThread().getContextClassLoader().getResourceAsStream("test.properties");

2、 基于InputStream

注意:该方式的优点在于可以读取任意路径下的配置文件

1     Properties properties = new Properties();
2     // 使用InPutStream流读取properties文件
3     BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\config.properties"));
4     properties.load(bufferedReader);
5     // 获取key对应的value值
6     properties.getProperty(String key);

3、基于java.util.ResourceBundle

这种方式比使用 Properties 要方便一些

通过 ResourceBundle.getBundle() 静态方法来获取(ResourceBundle是一个抽象类),这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可

1    properties.getProperty(String key);
2     //读取 classpath 路径下的 i18n/exception/CoframeMessagesmy.properties 文件
3     ResourceBundle resource = ResourceBundle.getBundle("i18n.exception.CoframeMessages",local);
4     String key = resource.getString("keyWord"); 
posted @ 2020-05-06 19:57  山那边风景  阅读(220)  评论(0编辑  收藏  举报