Java开发基础——配置文件的写入与读取

       在实际的项目开发中,配置文件是一个非常重要的工具,我们可以把全局的配置写入文件,然后在需要的时候再取出来。且在项目的任何位置都可以使用,非常方便。可以把配置文件理解为一个临时性的数据库。在IDEA中,配置文件的后缀为properties。本篇博客将会来演示在Java中配置文件的写入与读取:

配置文件如下图所示:



      我们一般把配置文件放入到resource文件夹中,作为一种资源文件。在IDEA中的资源文件如下图:



      目前我的配置文件内容只有两条如下,且命名为test.properties:

name=chenyufeng
age=25

(1)读取配置文件

    public void readProperty() throws IOException {
        //读取配置
        InputStream inputStream = ContractUtil.class.getClassLoader().getResourceAsStream("test.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        System.out.println("name = " + properties.getProperty("name"));
        System.out.println("age = " + properties.getProperty("age"));
    }

打印的结果如下,读取配置成功:



(2)写入配置文件:

       写入配置文件有两种思路,对于已经存在的键值,如果再次输入,是进行修改呢还是再添加一条。一般正确的思路是修改原来的键值。因为项目是需要键值唯一的,否则在进行读取的时候就会有问题。我下面会同时实现这两种方式:

    public void writeProperty() throws IOException {
        //写配置文件:这种方式会不断写入相同键值的数据,不推荐
//        Properties p = new Properties();
//        URL url = ContractUtil.class.getClassLoader().getResource("test.properties");
//        FileOutputStream fileOutputStream = new FileOutputStream(new File(url.getFile()), true);
//        p.setProperty("name", "Robert");
//        p.store(fileOutputStream, "");
//        fileOutputStream.close();


        //这种方式有键值的会修改,否则创建键值,修改后的配置文件查看target目录
        Properties properties = new Properties();
        URL url = ContractUtil.class.getClassLoader().getResource("test.properties");

        File file = new File(url.getFile());
        InputStream fis = new FileInputStream(file);
        properties.load(fis);
        //一定要在修改值之前关闭fis
        fis.close();
        OutputStream fos = new FileOutputStream(url.getFile());
        properties.setProperty("name", "Robert");
        properties.setProperty("age", "26");
        //保存,并加入注释
        properties.store(fos, "");
        fos.close();
    }

       上述代码的注释部分是遇到键相同的情况会新插入一条数据,会导致同一个配置文件中出现相同的键,不同的值。 未注释部分是遇到键匹配的情况时,会修改原来的键值。执行以上代码后,配置文件已经被修改成功(注意此时要去target目录下查看配置文件,而不是在resources目录下,resources下的test.properties是不会改变的 ):



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值