黑马程序员-Properties-

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

Properties

父类:HashTable

其键值对都是字符串。

功能:配置软件的属性或参数。

存取操作-setget

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

使用Propertiesload()方法

// 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();
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值