java基础之Properties

package com.j2se.propertiesDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

/*
 * 学习properties:类似于map集合,以键值对的形式存储数据
 */
public class PropertiesDemo {

	public static void main(String[] args) throws Exception{
		//printDemo();
		printCountDemo();
	}
	/**
	 * 打印出文本文件中的内容:前提是配置文件以键值对的形式存储
	 */
	public static void printDemo()throws Exception{
		File file=new File("src/demo.txt");
		Properties properties= new Properties();
		properties.load(new FileInputStream(file));
		String name= properties.getProperty("name");
		String gender=properties.getProperty("gender");
		String age=properties.getProperty("age");
		System.out.println("age="+age);
		//配置文件加载到内存中,我们修改的只是内存中的properties,并没有作用到文件中
		properties.setProperty("age", "23");
		FileOutputStream fos=new FileOutputStream(file);
		properties.store(fos, "这是注释");
		System.out.println(properties);
	}
	/**
	 * 实现计数器效果:properties配置文件中是应用程序共享的效果。
	 * 在web程序中,当应用程序停止时,将当前count计数器的数据保存到配置文件中,下次启动运行时有自动加1
	 * 下面我们可以写一个计数器来实现注册次数不能超过5次
	 */
	public static void printCountDemo() throws Exception{
		File file=new File("src/count.ini");
		if(!file.exists()){
			file.createNewFile();
		}
		FileInputStream fis=new FileInputStream(file);
		Properties properties=new Properties();
		properties.load(fis);
		int counter=0;
		String count= properties.getProperty("counter");
		if(count!=null){
			counter=Integer.parseInt(count);
			if(counter>=5){
				System.out.println("亲,对不起,您注册已经超过5次");
				return;
			}
		}
		counter++;
		properties.store(new FileOutputStream(file), "这是计数器");
		fis.close();
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值