解析Properties.store
时间: 2023-07-25 09:20:47 浏览: 53
`Properties.store` 方法是用于将属性列表(键和元素都是字符串)写入到输出流中的方法。通常,这个输出流是一个文件输出流或字节输出流。
方法定义如下:
```java
public void store(OutputStream out, String comments) throws IOException
```
其中参数 `out` 是一个字节输出流对象,表示要写入属性列表的输出流,参数 `comments` 是一个字符串,表示注释,可以为null。
`Properties.store` 方法将属性列表以键值对的形式写入到输出流中,格式为:
```
# comments
# 时间戳
key1=value1
key2=value2
...
```
其中,注释部分以`#`开头,时间戳表示写入文件的时间,键和值用`=`分隔。
示例代码如下:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesStoreDemo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("name", "Tom");
properties.setProperty("age", "18");
try {
FileOutputStream fos = new FileOutputStream("config.properties");
properties.store(fos, "This is a config file");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们创建了一个 `Properties` 对象,向其中添加了两个属性,然后将其存储到文件 `config.properties` 中,并在文件开头添加了注释 `"This is a config file"`。