课堂编程实践
假设硬盘上有一个test.properties文件 ,内容如何:Font-size=14px
language=chinese
Background-color=red
要求:遍历输出该文件内容,并向该文件写入charset=UTF-8配置项。
package At;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
public class Example {
public static void main(String[] args) {
//1.通过Properties进行属性文件读取操作
Properties pps=new Properties();
//加载要读取的文件test.properties
pps.load(new FileInputStream("test.properties"));
//遍历test.properties键值对元素信息
Enumeration names=pps.propertyNames();//获取 Enumeration对象所有键枚举
while(names.hasMoreElements()) {
String key=(String)names.nextElement();
String value =pps.getProperty(key);
System.out.println(key+":"+value);
}
//2.通过Properties进行属性文件写入操作
//指定要写入操作的文件名称和位置
FileOutputStream out=new FileOutputStream("test.properties");
//向Properties类文件进行写入键值对信息
pps.setProperty("charset","UTF-8");
//将此Properties集合中新增键值对信息写入配置文件
pps.store(out,"add charset code");
}
}