java io软件试用次数练习

模拟一个场景,一款软件的试用次数是10,超过试用次数,再次使用会提示超过试用次数

分析,需要先将试用次数写入到一个配置文件中,为了防止用户修改,对文件加密处理下(异或),然后每次运行程序会读取配置文件,先解密,判断用户试用次数是否超过10次,如果没超过10次,将试用次数做自减运算,再加密后写入到配置文件

package chen_Chapter8_io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TrialTest {
	public static void main(String[] args) {
//		encode();
		decode();

	}
//从配置文件读取信息,解密后判断是否超过试用次数,不超过时,将试用次数自减,再加密保存,超过时,提示用户超过试用次数
	private static void decode() {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream("config.ini"));
			int temp = bis.read();
			temp = temp ^ 54;
			if (temp > 0 && temp <= 10) {

				System.out.println("您的使用次数还剩余" + temp + "次");
				temp--;
				bos = new BufferedOutputStream(new FileOutputStream("config.ini"));
				bos.write(temp ^ 54);
				bos.flush();
			} else {
				System.out.println("您的使用次数已达到10次");
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
//将试用次数写入配置文件,运行一次就可以了
	private static void encode() {
		BufferedOutputStream bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream("config.ini"));
			// 对试用次数做加密处理
			bos.write(10 ^ 54);
			bos.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				// 避免空指针异常
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

配置文件保存在工程目录下:

原文:http://www.monkey1024.com/javase/626

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值