#头条创作挑战赛#一、先介绍properties配置文件 properties配置文件: 1.以键值对的形式书写 2. 每个键值对只能占据一行,否则当做一个键值对处理。 3.不要有重复的键,但可以有重复的值。 4.不用写双引号,否则读取的时候双引号也会被读取到,你自己要用双引号除外哈。 5.配置文件的后缀为 .properties 6.键值对不用写分号结尾。 7.以井号#进行注释。# 我是一个注释 cname=org.example.dao.User cage=18 二、properties类应用 properties类和properties文件是两码事哈! properties类是专门处理以后缀.properties的文件;properties类是双列集合,内容是键值对的形式。 例如:在idea的resources中建立一个abc.properties的文件,内容如下cname=org.example.dao.User cage=18 api:load(InputStream in):从输入字节流中读取键值对到properties对象 getProperty(String key):从properties集合中查询属性 setProperty(String key , String value): 设置键值对,这个只是将键值对写入properties对象中,并没有写入到properties文件中。 store(OutputStream out, String comments):将设置的键值对,写入到properties文件中。与setProperty是同用的。comments参数是备注,在文件中以#备注显示。 properties文件有了,java该怎么读取呢? 举例: 1、在main函数中先获取properties文件路径 String path = ClassLoader.getSystemClassLoader().getResource("abc.properties").getPath(); 2、将properties文件读取到内存中 String path = ClassLoader.getSystemClassLoader().getResource("abc.properties").getPath(); FileInputStream fr = new FileInputStream(path); 以上两句也可以写成:InputStream fr = ClassLoader.getSystemClassLoader().getResourceAsStream("abc.properties"); 3、创建properties类准备进行接收流文件String path = ClassLoader.getSystemClassLoader().getResource("abc.properties").getPath(); FileInputStream fr = new FileInputStream(path); Properties profile = new Properties(); 4、将流加载保存进profile对象中,因为流是字节,需要转成profile的双列集合对象对其管理。String path = ClassLoader.getSystemClassLoader().getResource("abc.properties").getPath(); FileInputStream fr = new FileInputStream(path); Properties profile = new Properties(); profile.load(fr); fr.close(); // 关闭输入流 5、增加属性到properties文件String path = ClassLoader.getSystemClassLoader().getResource("abc.properties").getPath(); FileInputStream fr = new FileInputStream(path); Properties profile = new Properties(); profile.load(fr); fr.close(); // 关闭输入流 profile.setProperty("sex","nan"); FileOutputStream outputStream = new FileOutputStream(path); profile.store(outputStream,"woshibeizhu"); outputStream.close(); 结果: properties文件中不能写入汉字,否则会自动转成Unicode编码。profile.setProperty("sex","南京离开的减肥啦的健康"); FileOutputStream outputStream = new FileOutputStream(path); profile.store(outputStream,"woshibeizhu"); outputStream.close(); 在idea中怎么解决乱码呢? 在file--setting--file Encodings