一、Properties
Properties是一种文本格式。里面的数据有自己规定的格式,一般存放键值对类型的数据。
优点: 可以很好很方便的跟java程序进行交互。java提供专门跟properties交互的API。存到properties文件中的内容是可以持久化的。
二、使用
- 里面的注释是使用#
- 键值之间一般使用=分割。也可以使用:号跟空格分割,但是尽量使用=号。
下面是创建的一个properties文件的截图
三、JAVA和properties文件的交互
3.1 数据的读取
// 1, java --- IO --- 硬盘上的文件
File file = new File("day04-02/src/hello.properties");
FileInputStream fis = new FileInputStream(file);
// 2, java 已经帮我们定义好了Properties类
Properties p = new Properties();
p.load(fis);
// 枚举器(Hashtable Vector)
Enumeration<Object> keys = p.keys();
while (keys.hasMoreElements()){
String key = (String) keys.nextElement();
System.out.println(key + " = " + p.getProperty(key) );
}
3.2 数据的存储
// 1,创建我们要保存的文件,如果不存在就创建这个文件
File f = new File("day04-02/src/hello2.properties");
if(!f.exists()){
f.createNewFile();
}
FileOutputStream fos = new FileOutputStream(f);
// 准备要保存的数据集合
Properties p = new Properties();
p.setProperty("name","刘备");
p.setProperty("age","35");
p.setProperty("sex","男");
// 将集合中的数据直接存储到文件中
p.store(fos,"曹操");
3.3 扩展
获取资源文件的流我们还可以通过InputStream fis = Demo03.class.getClassLoader().getResourceAsStream(“hello.properties”);方式。但是这种方式会将数据缓存到虚拟机中,如果缓存有数据则使用,没有则读取文件。
四、 案例
需求:模拟一个软件试用期的案例,比如一个程序如果使用了5天(次)就提示“试用已结束,请购买正版”,不足5次则可以继续使用。
public static void main(String[] args) throws Exception {
//1.第1次,配置文件如果不存在就创建这个文件
File f = new File("day04-02/src/software.properties");
if(!f.exists()){
f.createNewFile();
}
//2.把配置文件中的属性读取出来
FileInputStream fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
fis.close();
//3.读取参数,如果时null说明是第一次使用,则初始化次数为1,保存到配置文件中。
String count = p.getProperty("count");
if(Objects.isNull(count)){
count = "1" ;
p.setProperty("count" ,count);
}else{
//4.如果不是第一次使用,则取出这个值,增加1,然后再保存进去
int i = Integer.parseInt(count);
if(i>=5){
//5.保存的数据如果超过5次则提示
System.out.println("使用次数超过5次,请购买正版");
return ;
}
i++ ;
p.setProperty("count" ,""+i);
}
//6.把次数的数据存储到数据文件中
FileOutputStream fos = new FileOutputStream(f);
p.store(fos,"");
fos.close();
}
注意事项:
当既有读取又有存储的时候:
请注意一个问题:先用完一个管子(流),然后把这个管子关闭。
然后再开另外一个管子(流),用完再关闭。
请不要同时开2个管子(流)。