IO流_04(properties集合)

特点

  1. 该集合中的建和值都是字符串类型。
  2. 集合中的数据可以保存到流中,或者从流中获取。

通常该集合用于操作以键值对形式存在的配置文件。

基本操作

public class PropertiesDemo {

	public static void main(String[] args) throws IOException {
		Properties properties = new Properties();
		
		//存储元素
		properties.setProperty("name", "张三");
		properties.setProperty("sex", "male");
		properties.setProperty("age", "20");
		properties.setProperty("telephone", "18235271234");
		
		//取出一个元素
		String property = properties.getProperty("name");
		System.out.println(property);
		
		//修改元素
		//properties.setProperty("age", "21");
		
		//取出所有元素
		Set<String> names = properties.stringPropertyNames();
		for (String name : names) {
			String value = properties.getProperty(name);
			System.out.println(name+":"+value);
		}
	}
}

properties集合与流对象相结合的功能

	//向控制台打印所有元素
	properties.list(System.out);
	
	//把集合中的数据存入文件中
	properties.store(new FileOutputStream("E:\\黑马\\1.txt"), "User info");
	
	//把文件中的数据加载到集合中
	properties.load(new FileInputStream("E:\\黑马\\1.txt"));
	properties.list(System.out);

实例

设置应用程序只允许使用五次,之后必须得注册才可以用

	private static void listener() throws IOException {
		
		File file = new File("E:\\黑马\\2.txt");
		if(!file.exists()) {
			file.createNewFile();
		}
		
		Properties prop = new Properties();
		prop.load(new FileReader(file));
		String time = prop.getProperty("time");
		int count = 0;
		if(time != null) {
			count = Integer.parseInt(time);
			if(count >= 5)
				throw new RuntimeException("您的试用次数已用完,请注册");
		}
		
		count++;
		prop.setProperty("time", count+"");
		prop.store(new FileWriter("E:\\黑马\\2.txt"), "this is a count");
	}

猜你喜欢

转载自blog.csdn.net/cw13223/article/details/84948056
今日推荐