黑马程序员---Properties 实现程序计数注册功能

来源:互联网 发布:手机淘宝怎么改成差评 编辑:程序博客网 时间:2024/06/09 16:35

---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------

1.Properties 类怎么用的 无非是从一个文件读取数据到这个类中 操作这个类并写回去 以达到修改文件的作用
2.properties对文件内容是要求的 要像 建=数值 这样的数据
3.properties其实就是 io+map 就是把数据读来 放到map中

先说个properties的一个小实例

    public static void infoTest() throws Exception {        BufferedReader bf = new BufferedReader(new FileReader("D:\\info.txt"));        String line = null;        Properties prop = new Properties();        while ((line = bf.readLine()) != null) {            String[] arr = line.split("=");            prop.setProperty(arr[0], arr[1]);        }        Set<String> sets = prop.stringPropertyNames();        for (String s : sets) {            System.out.println(s + "=" + prop.getProperty(s));        }    }


这就是properties底层简单原理 读取Key=Value 这样的值放到properties (map)中 properties中的load()就完成这件事

下面说本帖的重点
完成这样一个功能 一个软件如果用3次就必须去注册
1.你想到的一定是 计数器 但计数器是当你启动程序计数器运行 你关闭程序计数器就会有回到原来的状态 这样就完不成这个功能
2.你可以把一个值写的一个文件中 key=value 然后程序启动时读取这个文件拿到值 进行判断等功能 (用的properties类)

功能代码

  public static void countTest() throws Exception {        Properties prop = new Properties();        // 文件操作 1.就好 File file = new File("D;\\info.txt"); 封装成对象 2.判断是否存在        File file = new File("d:\\info.ini");        if (!file.exists())            file.createNewFile();        FileInputStream fis = new FileInputStream(file);        prop.load(fis);// 加载        String value = prop.getProperty("count");        int count = 0;        if (value != null) {            count = Integer.valueOf(value) + 1;            if (count >= 3) {                // 这来实现功能                System.out.println("请去注册");                return;            }        }        prop.setProperty("count", String.valueOf(count));        FileOutputStream fos = new FileOutputStream(file);        prop.store(fos, "nihoa");// 这个方法是把数据覆盖info.txt的数据 第二个参数是注释        fos.close();        fis.close();    }


---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------

原创粉丝点击