当前位置:编程学习 > JAVA >>

求大神解答

位置1和位置2有什么区别呢?
为何放到位置1数据一直停留在1,存不进去,放到位置2就可以了呢?


public static void main(String[] args) throws Exception
{
properitiesTest();
}

private static void properitiesTest() throws IOException 
{
//创建文件对象
File confie = new File("confie.properties");

//判断文件是否存在,如果不存在重新创建
if(!confie.exists())
{
confie.createNewFile();
}
//包装文件
FileInputStream fis = new FileInputStream(confie);
//位置1-》 FileOutputStream fos = new FileOutputStream(confie);
//创建Properties对象
Properties pro = new Properties();

//用Properties对象加载文件,取得数据
pro.load(fis);
//创建一个计数器变量,一个String变量取得数据用于判断alue值是否为空
int count = 0;
String s = pro.getProperty("count");
//判断取得数据是否为空
if(s != null)
{
count = Integer.parseInt(s);
System.out.println("if"+count);
if(count >= 5)
throw new RuntimeException("使用已经超过5次,请用正版软件");
}
//如果为空,或者使用次数没有超过5次,则计数器加加
count++;
System.out.println(count);
//改变后的数据重新写入其中
FileOutputStream fos = new FileOutputStream(confie); //位置2-》
pro.setProperty("count", count+"");

//存入其中
pro.store(fos, "");
//关闭资源
fis.close();
fos.close();
} --------------------编程问答-------------------- 暂时不知道原因,不过楼主有没有注意,位置1的时候是没有if里面的东西没有执行,所以我们大胆推测一下,他没有把count放入properties文件里面,所以每一次都执行了int count = 0;然后在count++,所以每一次都输出1 --------------------编程问答-------------------- 原因是:FileInputStream有文件锁,他在的时候不能操作其他流 --------------------编程问答-------------------- FileOutputStream fos = new FileOutputStream(confie);// 位置1
因为文件锁的原因这句必须写在
pro.load(fis);的后面
--------------------编程问答-------------------- 多线程里有个读、写锁的概念   当一个线程加了写锁以后 是不允许其他线程来进行读和写的

同理如果把FileOutputStream fos = new FileOutputStream(confie); 放在位置1,就相当于给confie加了个写锁  他就不允许其他线程进行读了   所以pro.load(fis);就读不到数据了

ls说的是对的 我只是补充下原因
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,