1. properties的特点和作用
- 都只能是以键值对的方式存储
- 键不能重复
- 文件后缀一般是.priperties结尾的文件
2. 解决properties读取中文乱码的问题
* 第二步:设置读取数据的编码格式
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(SRC_FILE), "UTF-8"))
2. 读取文件数据【Properties】
Properties是一个Map集合(键值对集合),但是我们一般不会当集合使用。
核心作用:Properties是用来代表属性文件的,通过Properties可以读写属性文件里的内容。
构造器 | 说明 |
---|
public Properties() | 用于构建Properties集合对象(空容器) |
方法 | 说明 |
---|
public void load(InputStream inputStream) | 通过字节输入流,读取属性文件里的键值对数据 |
public void load(Reader reader) | 通过字符输入流,读取属性文件里的键值对数据 |
public String getProperty(String key) | 根据键获取值(其实就是get方法的效果) |
public Set stringPropertyNames() | 获取全部键的集合(其实就是keySet方法的效果) |
public class PropertiesTest1 {
private static final String SRC_FILE = "special-file\\src\\com\\ming\\users.properties";
public static void main(String[] args) {
try (
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(SRC_FILE), "UTF-8"))
) {
Properties properties = new Properties();
System.out.println(properties);
properties.load(bufferedReader);
System.out.println(properties.getProperty("zhangsan"));
Set<String> keys = properties.stringPropertyNames();
System.out.println(keys);
for (String key : keys) {
System.out.println(key + "->" + properties.getProperty(key));
}
properties.forEach((k, v) -> {
System.out.println(k + "->" + v);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 写入文件数据【Properties】
构造器 | 说明 |
---|
public Properties() | 用于构建Properties集合对象(空容器) |
方法 | 说明 |
---|
public Object setProperty(String key, String value) | 修改、设置properties数据 |
public void store(OutputStream outputStream, String comments) | 把键值对数据通过字节输出流写入properties文件中 |
public void store(Writer writer, String comments) | 把键值对数据通过字符输出流写入properties文件中 |
public class PropertiesTest2 {
private static final String SRC_FILE = "special-file\\src\\com\\ming\\users2.properties";
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("name", "张三");
properties.setProperty("age", "32");
properties.setProperty("sex", "男");
properties.store(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(SRC_FILE), "UTF-8")), "用户类");
}
}