Properties集合学会Properties集合的使用,添加两个元素分别为: fruit=apple,animal=cat,并将Properties保存到fileName中
时间: 2024-02-17 11:03:01 浏览: 110
好的,以下是Java示例代码,演示如何使用Properties集合实现上述操作:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) {
Properties prop = new Properties();
prop.setProperty("fruit", "apple");
prop.setProperty("animal", "cat");
try (FileOutputStream fos = new FileOutputStream("fileName")) {
prop.store(fos, "My Properties");
System.out.println("Properties saved.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码中,首先创建了一个Properties对象prop,并使用setProperty()方法向其中添加了两个键值对。然后,通过FileOutputStream类创建一个输出流,将Properties对象保存到指定的文件fileName中。最后,使用store()方法将Properties对象写入输出流中,并附带了一个注释字符串"My Properties"。如果保存成功,则输出"Properties saved."。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)