黑马程序员技术交流社区
标题:
Properties的方法load问题
[打印本页]
作者:
曾宇
时间:
2016-5-19 11:51
标题:
Properties的方法load问题
public void show()throws IOException{
//创建properties属性集对象
Properties proper = new Properties();
//创建File对象,目标地址
File file = new File("count.ini");
System.out.println(file.getAbsolutePath());
//如果file对象指向的不是一个文件
if(!file.exists()){
//创建文件对象,如果已经存在,不创建
file.createNewFile();
}
System.out.println(file);
//使用File对象创建输入流
FileInputStream fis = new FileInputStream(file);
//使用File对象创建输出流
FileOutputStream fos = new FileOutputStream(file);
//用properties对象读取输入流
proper.load(fis);
System.out.println(proper);
//定义计数器
int count = 0;
//读取输入流后,用properties对象获取指定键的值。
String value = proper.getProperty("time");
//如果值不为null
if(value!=null){
//用count计数器记录value的值。
count = Integer.parseInt(value);
if(count>3){
System.out.println("请注册使用!");
return;
}
}
//计数器自增
count++;
//用properties对象设置指定键的值
proper.setProperty("time", count+"");
//将properties对象存储到指定输出流
proper.store(fos, "");
fis.close();
fos.close();
}
复制代码
运行结果:
D:\Genuitec\Workspaces\IO\count.ini
count.ini
{}
load方法没有获取到任何键值对。
不管运行多少次也是一样的。value永远为null。
不知道我什么地方写错了,还是其它原因。
求大神解答
作者:
曾宇
时间:
2016-5-19 13:16
本帖最后由 曾宇 于 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() 方法返回与此文件输出流关联的唯一文件通道对象。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2