public class PropertiesDemo {
public static void main(String[] args)throws IOException {
//myStore();
// myLoad();
//myStoreTwo();
myLoadTwo();
}
private static void myLoad() throws IOException{
Properties prop = new Properties();
FileReader fr = new FileReader("src\\fr.txt");
//void Load(Reader reader):
// 从输入字符流**读取**属性列表(键和元素对)
prop.load(fr);
//使用Properties可以通过字符流读取文件中的数据
System.out.println(prop);
}
private static void myStore() throws IOException {
Properties prop = new Properties();
prop.setProperty("001","王");
prop.setProperty("002","邱");
prop.setProperty("003","折");
//void store(Writer writer,String commens):
// 将此属性列表(键和元素对)写入此Properties表中,
// 以适合使用Load(Reader)方法的格式写入输出字符流
FileWriter fw = new FileWriter("src\\fr.txt");
prop.store(fw,null);
fw.close();
}
private static void myStoreTwo()throws IOException{
Properties prop = new Properties();
prop.setProperty("001","王");
prop.setProperty("002","邱");
prop.setProperty("003","折");
//void store(OutputStream out , String commens):
// 将此属性列表(键和元素对)写入此Properties表中,
// 以适合用于使用load(InputStream)方法的格式写入输出字节流。
FileOutputStream fis = new FileOutputStream("src\\fis.txt");
prop.store(fis,null);
fis.close();
}
private static void myLoadTwo() throws IOException{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("src\\fis.txt");
//void Load(InputStream inStream):
// 从输入字节流读取属性列表(键和元素对)
prop.load(fis);
System.out.println(prop);
}
}
使用字符流,将Properties中的内容写入到文件的时候不会出现乱码,文件中的内容为
#Fri Mar 04 09:57:42 CST 2022
001=王
002=邱
003=折
使用字节流,将Properties中的内容写入到文件的时候,汉字会出现乱码,文件的内容为
#Fri Mar 04 10:08:22 CST 2022
001=\u738B
002=\u90B1
003=\u6298
但是在控制台输出的时候,
{001=王, 002=邱, 003=折}
用字节输入流可以正常读取,可以正常显示汉字。