A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 曾宇 中级黑马   /  2016-5-19 11:51  /  1128 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public void show()throws IOException{
  2.                 //创建properties属性集对象
  3.                 Properties proper = new Properties();
  4.                 //创建File对象,目标地址
  5.                 File file = new File("count.ini");
  6.                 System.out.println(file.getAbsolutePath());
  7.                
  8.                 //如果file对象指向的不是一个文件
  9.                 if(!file.exists()){
  10.                         //创建文件对象,如果已经存在,不创建
  11.                         file.createNewFile();
  12.                 }
  13.                 System.out.println(file);
  14.                 //使用File对象创建输入流
  15.                 FileInputStream fis = new FileInputStream(file);
  16.                 //使用File对象创建输出流
  17.                 FileOutputStream fos = new FileOutputStream(file);
  18.                 //用properties对象读取输入流
  19.                 proper.load(fis);
  20.                 System.out.println(proper);
  21.                 //定义计数器
  22.                 int count = 0;
  23.                 //读取输入流后,用properties对象获取指定键的值。
  24.                 String value = proper.getProperty("time");
  25.                 //如果值不为null
  26.                 if(value!=null){
  27.                         //用count计数器记录value的值。
  28.                         count = Integer.parseInt(value);
  29.                         if(count>3){
  30.                                 System.out.println("请注册使用!");
  31.                                 return;
  32.                         }
  33.                 }
  34.                 //计数器自增
  35.                 count++;
  36.                 //用properties对象设置指定键的值
  37.                 proper.setProperty("time", count+"");
  38.                 //将properties对象存储到指定输出流
  39.                 proper.store(fos, "");
  40.                 fis.close();
  41.                 fos.close();
  42.                
  43.         }
复制代码


运行结果:
D:\Genuitec\Workspaces\IO\count.ini
count.ini
{}


load方法没有获取到任何键值对。
不管运行多少次也是一样的。value永远为null。
不知道我什么地方写错了,还是其它原因。
求大神解答

1 个回复

倒序浏览
本帖最后由 曾宇 于 2016-5-19 13:23 编辑

这个问题已经解决了。
问题原因:
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file);
同一时间只能有一个流对象指向file。
fis,fos同时指向一个文件对象,会抢夺文件通道。
然后fis对象就悲剧了,文件通道被抢了。
虽然fis指向的还是file文件,但是没有文件通道,所以什么都没读取到。
java.io.FileOutputStream.getChannel() 方法返回与此文件输出流关联的唯一文件通道对象。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马