Java读取和写入配置文件Properties

本文介绍了如何使用Java读取my.properties配置文件,动态修改配置项后,将更改写回配置文件的过程。展示了Properties类的使用和文件I/O操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java读取和写入配置文件Properties

假如项目有一个配置文件my.properties,里面的初始默认配置是:

现在加载并读取这些配置项,并通过上层Java代码重新设置配置项目,然后写回到my.properties配置文件里面:

package org.example;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.util.Properties;

public class MainClass {
    private static void readConfig(){
        try {
            //读取所有配置

            Properties properties = new Properties();
            Reader reader = new FileReader("./my.properties");
            properties.load(reader);

            System.out.println(properties.getProperty("server.host"));
            System.out.println(properties.getProperty("server.port"));

            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        readConfig();

        System.out.println("---");

        try {
            //重新配置,然后写入配置文件

            Properties properties = new Properties();
            properties.setProperty("server.host", "127.0.0.1");
            properties.setProperty("server.port", "8080");

            FileWriter fileWriter = new FileWriter("./my.properties");
            properties.store(fileWriter, "new set");
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        readConfig();
    }
}

运行输出:

0.0.0.0
80
---
127.0.0.1
8080

修改后的配置文件内容:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值