黑马程序员技术交流社区
标题:
读取硬盘上Properties文件的问题。
[打印本页]
作者:
寇弘禄
时间:
2013-4-6 10:39
标题:
读取硬盘上Properties文件的问题。
本帖最后由 张熙韬 于 2013-4-6 21:32 编辑
这段代码为什么计数器不自增呢?
public class RunCountDemo {
/**
* 定义一个程序用于记录软件的使用次数。
* 思路是在硬盘上定义一个配置文件,通过键值对的形式存储。
* 1 定义一个Properties集合
* 2 定义一个字节流将配置文件的数据加载进集合。
* 3 通过键tiem获取已使用次数。
* 4 定义一个计数器。
* 5如果获取到的值不为空则将此值付给计数器,先判断此值是否小于5,如果不小于5,则退出,否则计数器自增后将键和值存入。
* 6否则计数器自增后将键和值存入。
* 7定义输出流将配置文件输出。
* @throws IOException
*/
public static void main(String[] args) throws IOException {
RunCountMethod();
}
public static void RunCountMethod() throws IOException{
Properties prop = new Properties();
File file = new File("d:\\count.properties");
if(!file.exists()){
throw new RuntimeException("文件不存在");
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file);
int count = 0;
prop.load(fis);
String value = prop.getProperty("time");
if(value!=null){
System.out.println("value!=null");
count = Integer.parseInt(value);
if(count>=4){
System.out.println("使用次数已到,请付费");
return;
}
}
System.out.println("count=="+count); //为什么count总是0
count++;
prop.setProperty("time", count+"");
prop.store(fos, "");
fos.close();
fis.close();
}
}
复制代码
作者:
吴林飞
时间:
2013-4-6 11:35
本帖最后由 吴林飞 于 2013-4-6 11:39 编辑
import java.io.*;
import java.util.*;
public class RunCountDemo {
/**
* 定义一个程序用于记录软件的使用次数。
* 思路是在硬盘上定义一个配置文件,通过键值对的形式存储。
* 1 定义一个Properties集合
* 2 定义一个字节流将配置文件的数据加载进集合。
* 3 通过键tiem获取已使用次数。
* 4 定义一个计数器。
* 5如果获取到的值不为空则将此值付给计数器,先判断此值是否小于5,如果不小于5,则退出,否则计数器自增后将键和值存入。
* 6否则计数器自增后将键和值存入。
* 7定义输出流将配置文件输出。
* @throws IOException
*/
public static void main(String[] args) throws IOException {
RunCountMethod();
}
public static void RunCountMethod() throws IOException{
Properties prop = new Properties();
File file = new File("d:\\count.properties");
if(!file.exists()){
throw new RuntimeException("文件不存在");
}
FileInputStream fis = new FileInputStream(file);
//FileOutputStream fos = new FileOutputStream(file);
//你这里直接创建两个流和file关联有意义么,输入流中的数据还没有经过计数器自增操作,就直接转到输出流中
//计数器一直就没起作用。
int count = 0;
prop.load(fis);
String value = prop.getProperty("time");
if(value!=null){
System.out.println("value!=null");
count = Integer.parseInt(value);
if(count>=4){
System.out.println("使用次数已到,请付费");
return;
}
}
System.out.println("count=="+count); //为什么count总是0
count++;
FileOutputStream fos = new FileOutputStream(file);//
prop.setProperty("time", count+"");
prop.store(fos, "");
fos.close();
fis.close();
}
}
复制代码
作者:
寇弘禄
时间:
2013-4-6 14:19
吴林飞 发表于 2013-4-6 11:35
在上面定义了,到下面在用不行吗?不是读到 prop.store(fos, ""); 才用到这个fos流吗?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2