java 操作配置文件代码
时间: 2023-05-28 22:03:03 浏览: 85
以下是Java中操作配置文件的代码示例:
读取配置文件:
```java
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String value1 = props.getProperty("key1");
String value2 = props.getProperty("key2");
```
写入配置文件:
```java
Properties props = new Properties();
try {
OutputStream out = new FileOutputStream("config.properties");
props.setProperty("key1", "value1");
props.setProperty("key2", "value2");
props.store(out, "This is a configuration file.");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
```
更新配置文件:
```java
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
props.setProperty("key1", "new_value1");
try {
OutputStream out = new FileOutputStream("config.properties");
props.store(out, "This is a configuration file.");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
```
删除配置文件中的一个属性:
```java
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream("config.properties"));
props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
props.remove("key1");
try {
OutputStream out = new FileOutputStream("config.properties");
props.store(out, "This is a configuration file.");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
```
阅读全文