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

猜你喜欢

转载自blog.csdn.net/sinat_41132860/article/details/84396036
今日推荐