黑马程序员技术交流社区

标题: 可以帮我试运行一下么谢谢了,我找不出错误 [打印本页]

作者: 爽朗的菜籽    时间: 2014-10-12 15:24
标题: 可以帮我试运行一下么谢谢了,我找不出错误
  1. /*
  2. *  需求:运行程序运行五次之后,不可在运行,抛出 “使用次数已到,请购买正版”
  3. *  思路:将运行五次的信息存储到程序本身                useCount——5        这种形式,对应关系可以用类Properties来存储
  4. *          setProperty(k,v),读取文件信息,load(InputStream);存储配置信息,store(OutputStream),每次运行count+1
  5. */
  6. public class PropTest
  7. {
  8.         public static void main(String[] args) throws IOException
  9.         {
  10.                 File fileName = new File("d:\\propTest.properties");
  11.                 openFile(fileName);
  12.         }
  13.         public static void openFile(File fileName) throws IOException
  14.         {
  15.                 FileOutputStream fos = new FileOutputStream(fileName);
  16.                 Properties prop = new Properties();
  17.                 FileInputStream fis = new FileInputStream(fileName);
  18.                 prop.load(fis);
  19.                 String key = "useCount";
  20.                 System.out.println("判断了吗");
  21.                 if(prop.containsKey(key))
  22.                 {
  23.                         System.out.println("if----run");
  24.                         String value = prop.getProperty(key);
  25.                         int count = Integer.parseInt(value);
  26.                         if(count>4)
  27.                         {
  28.                                 throw new RuntimeException("已到使用次数上限");
  29.                         }
  30.                         count++;
  31.                         prop.setProperty(key, count+"");
  32.                         prop.store(fos, "");
  33.                 }else
  34.                 {
  35.                         System.out.println("else----run");
  36.                         prop.setProperty(key, 1+"");
  37.                         prop.store(fos, "");
  38.                 }
  39.                 fos.close();
  40.                 fis.close();
  41.         }       
  42. }
复制代码

作者: SelonLiao    时间: 2014-10-12 18:09
同学,问题找到了
每当你在创建 FileOutputStream fos = new FileOutputStream(fileName);  这个对象时,FileOutputStream的构造函数会将指定的文件删除掉,重新创建一个,所以才会出现每次运行时都是第一次访问,不会累加访问次数。

解决办法:
先执这段代码 prop.load(fis);  加载完文件后  ,再创建 FileOutputStream 对象,就样可以了。
                              
作者: 油油油菜花    时间: 2014-10-12 18:19
看看!!
作者: 琳以沫    时间: 2014-10-12 21:24
看看。。。
作者: yl82846094    时间: 2014-10-12 21:44
顶一个!
作者: Mr.Ni    时间: 2014-10-12 22:56
我就看看不说话。
作者: 爽朗的菜籽    时间: 2014-10-12 23:44
SelonLiao 发表于 2014-10-12 18:09
同学,问题找到了
每当你在创建 FileOutputStream fos = new FileOutputStream(fileName);  这个对象时,Fi ...

万分感谢,怎么送人黑马币,我技术分够了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2