黑马程序员技术交流社区

标题: 一个练习中的疑问 [打印本页]

作者: HelloWorld!    时间: 2014-12-5 01:04
标题: 一个练习中的疑问
问题:如注释中所示,流对象放在上面的位置,不管运行几次,配置文件中的time对应的值一直是1。why?
/*
* 编写一个程序,运行5次后就需要注册
*/
public class PropertiesDemo {

        public static void main(String[] args) throws IOException {
               
                Properties pro = new Properties();
                File f = new File("e:\\count.ini");
                if(!f.exists())
                        f.createNewFile();
                FileInputStream fis = new FileInputStream(f);
//                FileOutputStream fos = new FileOutputStream(f);    //放到这为啥不行?
                pro.load(fis);
                int count = 0;
                String value = pro.getProperty("time");
                if(value!=null){
                        count = Integer.parseInt(value);
                        if(count >=5)
                                System.out.println("请注册!");
                }
                count++;
                pro.setProperty("time", count+"");
                FileOutputStream fos = new FileOutputStream(f);       //放在这里却可以
                pro.store(fos,"");
                fis.close();
                fos.close();
               
        }

}



作者: kerner    时间: 2014-12-5 21:33

                FileInputStream fis = new FileInputStream(f);
//             FileOutputStream fos = new FileOutputStream(f);    //这条语句擦出了文件内容,导致getProperty()读取不到东西。 所以value为Null.
//     FileOutStream(String file) 如果有文件存在,则不创建新文件,但是会擦出文件内容。

                pro.load(fis);
                int count = 0;
                String value = pro.getProperty("time");
                if(value!=null){
                        count = Integer.parseInt(value);
                        if(count >=5)
                                System.out.println("请注册!");
                }
                count++;
                pro.setProperty("time", count+"");
                FileOutputStream fos = new FileOutputStream(f);       //放在这里却可以
                pro.store(fos,"");
                fis.close();
                fos.close();
作者: HelloWorld!    时间: 2014-12-6 04:36
kerner 发表于 2014-12-5 21:33
FileInputStream fis = new FileInputStream(f);
//             FileOutputStream fos = ...

明白了,非常感谢




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