程序的配置文件

程序的配置文件:简单的用properties 复杂的用 xml(文本型的数据库),而使用properties主要是五个方法:1、new ;2、set; 3、get; 4、load; 5、store;

开始时将配置文件放在与src文件夹并列的位置,bin下是运行根目录 会被src文件覆盖。

在paoperties中 # 表示注释

comments参数的作用是在配置文件中加一行#...的注释。

properties要用到io读写。所以要用到io流。对于io不熟悉可以看我前面的io流复习笔记。

下面我们通过两个个实例来理解这个知识点:

一、properties函数的演示

package cn.hncu.property;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {
	
	//使用Properties的五个函数 
	//因为load读入和store写出方法需要与外面的文件相关联,所以要用到io流。即io流的读与写。
	//这里用到的key与value都是string类型的
	public static void main(String[] args) {
		
		Properties proper=new Properties();//1 new方法
		FileInputStream fin=null;
		try {
			fin =new FileInputStream("qwer.txt");
			proper.load(fin);//2 load方法
			String str1=proper.getProperty("Sname");//3 get方法
			System.out.println(str1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileOutputStream fout=null;
		try {
			fout=new FileOutputStream("qwer.txt");
			proper.setProperty("information", "yiyang");//4 set方法
			proper.store(fout, null);//5 store方法
		} catch (IOException e) {
			System.out.println("error");
		}
		try {
			fin.close();
			fout.close();
		} catch (IOException e) {
			throw new  RuntimeException("关流失败");
		}
		
	}

}


二、小程序

实现代码如下

package cn.hncu.property;

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

import javax.management.RuntimeErrorException;

public class TimesTried {
	public static void main(String[] args) {
		//进入住函数的卫条件,防护
		if(countDemo()){
			System.out.println("欢迎使用***");
		}else{
			System.out.println("使用次数已到,无法继续使用");
		}
	}

	private static boolean countDemo() {
		int count=0;
		Properties p=new Properties();
		File f=new File("An.dat");
;		FileInputStream fin = null;
		try {
			fin=new FileInputStream(f);
			p.load(fin);
			String value=p.getProperty("count");
			count=Integer.parseInt(value);
			if (count>=5) {
				System.out.println("使用次数已到,请注册");
				return false;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		count++;
		System.out.println("运行次数为:"+count);
		//写
		FileOutputStream fout = null;
		try {
			p.setProperty("count", ""+count);
			fout=new FileOutputStream(f);
			p.store(fout, null);
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			fin.close();
			fout.close();
		} catch (IOException e) {
			throw new RuntimeException("关流失败");
		}
		return true;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值