Java配置文件读写示例
在Java中,我们通常使用Properties类来处理配置文件的读写。以下是一个简单的示例:
配置文件(config.properties):
server.port=8080
database.url=jdbc
//localhost:3306/testdb
database.username=root
database.password=
读取配置文件:
```java
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigReader {
public static void main(String[] args) {
// 创建Properties对象
Properties props = new Properties();
// 从文件中加载配置
try (FileInputStream fis = new FileInputStream("config.properties")) {
props.load(fis);
} catch (Exception e) {
System.out.println("Error reading config file: " + e.getMessage());
return;
}
// 获取配置信息
String serverPort = props.getProperty("server.port");
System.out.println("Server port: " + serverPort);
// 写入配置文件(示例,不实际操作)
// props.store(new FileOutputStream("config.properties")), "Update Config");
}
}
```
- 如果需要更新配置文件,可以将写入部分添加到程序中。
以上就是一个简单的Java配置文件读写示例。
还没有评论,来说两句吧...