黑马程序员技术交流社区

标题: properties存取练习发现的一个细节 [打印本页]

作者: 丰亚彬    时间: 2012-6-6 17:12
标题: properties存取练习发现的一个细节
在重新复习写到这个练习题的时候,发现了一个容易出错的,地方拿出来和大家分享一下
  1. import java.util.*;
  2. import java.io.*;
  3. class PropertiesDemo1
  4. {
  5.         public static void main(String[] args) throws IOException
  6.         {
  7.                 //判断文件是否存在。不存在就创建
  8.                 File file = new File("count.ini");
  9.                 if(!file.exists())
  10.                         file.createNewFile();
  11.                
  12.                 //对象初始化
  13.                 Properties prop = new Properties();
  14.                 FileInputStream fis = new FileInputStream(file);
  15.                 FileOutputStream fos = new FileOutputStream(file);


  16.                 //将键值对存到properties中并且处理
  17.                 prop.load(fis);
  18.                 int count = 0;
  19.                 String value = prop.getProperty("count");
  20.                 if(value!=null)
  21.                 {
  22.                         count = Integer.parseInt(value);
  23.                         if(count>3)
  24.                         {
  25.                                 System.out.println("time over");
  26.                                 return;
  27.                         }
  28.                 }
  29.                 count++;
  30.                 prop.setProperty("count",count+"");
  31.                 //这里的输出流要写到这里才能运行正确,写到上面就错了
  32.                 //FileOutputStream fos = new FileOutputStream(file);
  33.                 prop.store(fos,"");
  34.                 fis.close();
  35.                 fos.close();
  36.         }
  37. }
复制代码
一般我们都喜欢先把对象定义出来,但是那个输出流如果在开始定义了,那么你里面的值就一直都是空的,所以每次运行完都只是1,刚开始我也迷惑,后来想起来了,输出流会覆盖你原来的文件,所以每次都是一个新的文件,里面的内容都覆盖了
不知道有没有朋友有办法可以避免这样的问题?
作者: 罗文杰    时间: 2012-6-6 17:22
{:3_50:}我上午写的时候也犯了这个错误,一直是1,= =~~
作者: 伊文龙    时间: 2012-6-6 18:01
刚刚在楼主另一个相同的帖子上看到这个问题。
看到 你的问题和你代码中这一句FileOutputStream fos = new FileOutputStream(file)
然后我认为是 FileOutputStream fos = new FileOutputStream(file,true);才对,
后来一看是Properties的问题,以为自己回答的草率了,又试着运行了下
结果问题还是在那里~把输出流改成可添加就可以了
FileOutputStream fos = new FileOutputStream(file,true);
作者: 伊文龙    时间: 2012-6-6 18:04
我的运行三次的结果:

#
#Wed Jun 06 17:51:48 CST 2012
count=1
#
#Wed Jun 06 17:56:34 CST 2012
count=2
#
#Wed Jun 06 17:56:38 CST 2012
count=3

未count.jpg (32.42 KB, 下载次数: 18)

未count.jpg





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