配置文件简单应用

/*
 * 配置文件简单应用
 * 当用户试用的应用程序使用时间到达一定的天数提示用户购买,这需要用配置文件来保存试用次数
 */


package properties;


import java.io.*;
import java.util.Properties;


public class Properties_use {


public static void main(String[] args) {
//定义一个Properties对象,用于程序运行过程中配置文件的使用
Properties prop = new Properties();
File file = new File("count.properties"); //将配置文件封装成流文件
BufferedReader bufr = null;
if(!file.exists()) //首次使用创建文件
try {
file.createNewFile();
} catch (IOException creat) {
// TODO Auto-generated catch block
System.out.println("创建配置文件失败");
creat.printStackTrace();
}
try { //将文件包装到输入流
bufr = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException fileget) {
// TODO Auto-generated catch block
System.out.println("文件流获取失败");
fileget.printStackTrace();
}

try { //加载配置文件
prop.load(bufr);
} catch (IOException load) {
// TODO Auto-generated catch block
System.out.println("配置文件加载失败");
load.printStackTrace();
} finally { //关闭资源
try {
if(bufr != null)
bufr.close();
} catch (IOException close) {
// TODO Auto-generated catch block
close.printStackTrace();
throw new RuntimeException();

}
}

String value = prop.getProperty("count"); //获取使用次数
int count = 0; //记录使用次数

if(value != null){
count = Integer.parseInt(value); //记录以使用的次数

//在这里可以对使用次数限定
if(count >= 5){
System.out.println("试用期已到,请您购买后再使用");
return ;
}
}

count++; //修改使用次数
prop.setProperty("count", count + "");

BufferedWriter bufw = null;
try {
bufw = new BufferedWriter(new FileWriter(file));
} catch (IOException out) {
// TODO Auto-generated catch block
System.out.println("文件输出流创建失败");
out.printStackTrace();
}
try {
prop.store(bufw, null);
} catch (IOException store) {
// TODO Auto-generated catch block
System.out.println("配置文件保存失败");
store.printStackTrace();
} finally {
try {
if(bufw != null)
bufw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("输出资源释放异常");
e.printStackTrace();
}
}



}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值