Erlo

Java读取.properties配置文件

2018-10-17 11:48:10 发布   46 浏览  
页面报错/反馈
收藏 点赞

一、介绍

Properties文件在Java中主要为配置文件,文件类型为:.properties,格式为文本文件,内容格式为"键=值"

二、读取

这里我采用的是getResourceAsStream的文件读取方法

如果想要使用这个方法,则需要了解一些基本使用信息:

1、读取文件路径范围:只局限于工程的源文件中

2、文件访问形式:带"/"是绝对路径,不带"/"是相对路径

3、读取文件类型:主要为:.properties文件,.xml文件

三、使用

主要方法有:

1、 load ( InputStream  inStream) :从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如的 beans.properties 文件)进行装载来获取该文

件中的所有键 - 值对。

2、 setProperty ( String  key, String  value) :调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

3、 getProperty ( String  key) :用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。

4、 store ( OutputStream  out, String  comments) :以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素

对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

5、 clear ():清除所有装载的 键 - 值对。该方法在基类中提供。



java项目配置文件存放位置:

Maven项目配置文件存放位置:

 

配置文件:

className = edu.nf.ch02.impl.Sub

 

java代码:

public class Main {

    public static void main(String[] args) throws IOException {
        //创建Properties对象
        Properties prop = new Properties();
        //读取classPath中的properties文件
        prop.load(Main.class.getClassLoader().getResourceAsStream("bean.properties"));
        //根据键取出值
        String className = prop.getProperty("className");
        System.out.println(className);
        
    }
}

运行结果:

 

封装的PropertiesUtil工具类:

public class PropertyUtil {

    private static Properties prop = new Properties();

    static {
        try {
            prop.load(PropertyUtil.class.getClassLoader().getResourceAsStream("calculator.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据Name获取Property
     * @param name
     * @return
     */
    public static String getProperty(String name) {
        return prop.getProperty(name);
    }

    /**
     * 获取所有的Property
     * @return
     */
    public static List<String> getBeanFactoryClass() {
        List<String> list = new ArrayList<>();
        Set<String> keys = prop.stringPropertyNames();
        for (String key : keys) {
            list.add(prop.getProperty(key));
        }
        return list;
    }
}

 

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认