黑马程序员技术交流社区

标题: IO流中遇到了个异常疑惑的东西,求解决 [打印本页]

作者: 唐王潮    时间: 2014-10-8 12:31
标题: IO流中遇到了个异常疑惑的东西,求解决
本帖最后由 唐王潮 于 2014-10-8 12:51 编辑

请先看完代码
  1. package pro.properties;

  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.util.Properties;
  7. import java.util.Set;

  8. public class propertiesTest {

  9.         public static void main(String[] args) throws IOException {
  10.                 /*
  11.                  * 需求:定义一个功能,记录程序运行的次数。满足5此后,给出提示,试用次数已到,请注册!
  12.                  *
  13.                  */
  14.                 boolean b = checkCount();
  15.                 if(b){
  16.                         run();
  17.                 }
  18.         }

  19.         private static boolean checkCount() throws IOException {
  20.                 boolean isrun = true;
  21.                
  22.                 File configfile = new File("tempfile\\newinfo.propreties");
  23.                 if(!configfile.exists()){
  24.                         configfile.createNewFile();
  25.                 }
  26.                 int count = 0;
  27.                
  28.                 Properties prop = new Properties();
  29.                 FileInputStream fis = new FileInputStream(configfile);
  30. //             FileOutputStream fos = new FileOutputStream(configfile);//为什么放到此处 写入配置文件中的count的值总是为1??????
  31.                 prop.load(fis);
  32.                
  33.                 String value = prop.getProperty("count");
  34.                 if(value!=null){
  35.                         count = Integer.parseInt(value);
  36.                         if(count>=5){
  37.                                 System.out.println("给钱");
  38.                                 return false;
  39.                         }
  40.                 }
  41.                 count++;
  42.                 prop.setProperty("count", Integer.toString(count));
  43.                 FileOutputStream fos = new FileOutputStream(configfile);//放到此处没什么问题,正常
  44.                
  45.                 prop.store(fos,"app,time");
  46.                
  47.                
  48.                 return isrun;
  49.                
  50.                
  51.         }

  52.         private static void run() {
  53.                 System.out.println("程序运行");
  54.         }
  55.         
  56. }
复制代码

作者: 唐王潮    时间: 2014-10-8 19:41
zengming13 发表于 2014-10-8 15:15
因为你对一个文件同时打开输入流和输出流,导致后打开的流有效,先打开的输入流失效,导致配置文件不能正确 ...

非常感谢,根据你的回答,再加上自己的测试,确实如你所说,后打开的流会覆盖先打开的流。
作者: 琳以沫    时间: 2014-10-8 20:56
学习了。。。我也在学这块的知识了。。。
作者: 2406035442    时间: 2014-10-8 21:08
还没学。。。




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