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
修改后的配置文件内容: