使用Properties记录程序运行次数

本文介绍了一个简单的Java程序,该程序使用Properties类来记录程序的启动次数,并限制程序最多运行五次。通过读取和写入配置文件的方式,演示了如何在每次程序启动时更新并检查启动次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.tgx.file;

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

public class RunCount2 {
	
	private static FileInputStream fis = null;
	private static FileOutputStream fos = null;

	public static void main(String[] args) throws IOException {
				
		try {
			
			Properties prop = new Properties();//创建Properties对象
			
			File file = new File("count2.ini");//定义配置文件对象
			if(!file.exists()){
				
				file.createNewFile();
			}
			//创建文件流
			fis = new FileInputStream(file);
			
			//将文件里的信息载入到prop
			prop.load(fis);
			
			//获取Properties的键值
			String value = prop.getProperty("time");
			
			int count = 0;
			if(value!=null){
				
				count = Integer.parseInt(value);
				//判断程序是否已经使用了5次
				if(count>=5){
					
					System.out.println("您好!你使用的次数已经到了5次了,请注册...");
					return;//退出程序
				}
			}
			count++;
			
			//
			prop.setProperty("time", count+"");
			//将prop写出到file配置文件。
			fos = new FileOutputStream(file);
			prop.store(fos, "");
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			
			//关闭资源
			if(fis!=null){
				
				fis.close();
				fis = null;
			}
			if(fos!=null){
				
				fos.close();
				fis = null;
			}
		}
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值