------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
Properties
父类:HashTable
其键值对都是字符串。
功能:配置软件的属性或参数。
存取操作-set,get
setProperty(String key, String value)
输出方法list(PrintStream out)
将Properties对象中的属性列表输出到指定的输出流中。
将文件中的键值对存储到集合当中
解决思路1:
使用流一行行读取文件。
使用“=”将字符串切割开。
分别配置到键值中
// 使用流读取文件,然后将文件分割出来,使用serProperty(String key,String value)方法将数据录入到property对象中。
// 也是load(Reader reader) 方法的原理
public static void addFile() throws IOException {
BufferedReader bufr = new BufferedReader(new FileReader("D:\\马王\\properties.txt"));
String line = null;
Properties prop = new Properties();
while((line = bufr.readLine()) != null) {
// 使用String的split(String str)方法将字符串分隔开
String[] strs = line.split("=");
prop.setProperty(strs[0],strs[1]);
}
System.out.println(prop);
}
解决思路2:
使用Properties的load()方法
// Porperties集合可以加载字符流和字节流。
public static void loadFileByStream() throws IOException {
//BufferedReader bufr = new BufferedReader(new FileReader("D:\\马王\\properties.txt"));
FileInputStream in = new FileInputStream("D:\\马王\\properties.txt");
Properties prop = new Properties();
prop.load(in);
// list方法可以将属性列表输出到指定的输出流
prop.list(System.out);
}
指定key,修改Properties对象的内容-setProperty(key, value)
但是此方法只是修改了内存中的数据,对硬盘没有影响。
prop.setProperty("ccc","ChangedValue");
将修改后的属性序列存入文件中
store(OutputStream out / Writer out, Comment注释)
FileInputStream in = new FileInputStream("D:\\马王\\properties.txt");
Properties prop = new Properties();
prop.load(in);
prop.setProperty("ccc","ChangedValue");
FileOutputStream out = new FileOutputStream("D:\\马王\\properties.txt");
prop.store(out, "change it");
// list方法可以将属性列表输出到指定的输出流
prop.list(System.out);
需求:技术软件的使用次数,并将此数持久化到文件中
注意:对该文件使用流操作将其录入之前,需要将文件封装成File对象,并判断该文件是否存在!
package com.lxh.io.properties;
import java.io.*;
import java.util.*;
public class PropertiesCount {
/**
* 使用.ini或.properties文件记录次数,当到达此数目时,程序不能再运行
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//1.将文件封装成File对象,并判断该文件是否存在,不存在则创建该文件
Properties prop = new Properties();
File file = new File("D:\\马王\\count.ini");
if(!file.exists())
file.createNewFile();
FileReader fr = new FileReader(file);
prop.load(fr);
int count = 0;
String value = prop.getProperty("count");
System.out.println(value);
if(value!= null) {
count = Integer.parseInt(value);
}
count++;
prop.setProperty("count", count+"");
FileWriter fw = new FileWriter(file);
prop.store(fw,"");
fr.close();
fw.close();
}
}