黑马程序员技术交流社区
标题:
Hashtable子类Properties问题
[打印本页]
作者:
徐传任
时间:
2012-9-24 23:52
标题:
Hashtable子类Properties问题
//需求:用于记录应用程序运行的次数,如果使用次数已到,那么给出注册提示。
import java.io.*;
import java.util.*;
public class ProDemo
{
public static void main(String[] args) throws IOException
{
Properties pro = new Properties();
File f = new File("ProDemo.ini");
if(!f.exists())
f.createNewFile();
FileInputStream fr = new FileInputStream(f);
pro.load(fr);
int count=0;
String s = pro.getProperty("time");
if(s!=null)
{
count = Integer.parseInt(s);
if(count>=5)
{
System.out.println("您的使用次数已到,欢迎再次付费使用!!!");
return;
}
}
count++;
pro.setProperty("time", count+""); //这一步与下面的代码:pro.store(fw,"");有什么联系?
//这两步分别是什么意思呀??
FileOutputStream fw = new FileOutputStream(f);
pro.store(fw,"");
fr.close();
fw.close();
}
}
复制代码
作者:
赵永康
时间:
2012-9-25 00:19
你是不是最后又写到同一文件中了???
作者:
佘天宇
时间:
2012-9-25 00:56
//需求:用于记录应用程序运行的次数,如果使用次数已到,那么给出注册提示。
import java.io.*;
import java.util.*;
public class ProDemo
{
public static void main(String[] args) throws IOException
{
Properties pro = new Properties();
File f = new File("ProDemo.ini");
if(!f.exists())
f.createNewFile();
FileInputStream fr = new FileInputStream(f);
pro.load(fr);
int count=0;
String s = pro.getProperty("time");
if(s!=null)
{
count = Integer.parseInt(s);
if(count>=5)
{
System.out.println("您的使用次数已到,欢迎再次付费使用!!!");
return;
}
}
count++;
System.out.println("欢迎使用,次数有限,最多使用5次,你使用了:"+count+"次");
//可以在这里查看使用的次数,就是程序运行的次数
pro.setProperty("time", count+"");//这一步与下面的代码:pro.store(fw,"");有什么联系?
//这里的意思是改变后的count重新以"time"和count作为键和值存入pro集合中,
//没有这一步,那么文件中的值是不会改变的。就是说使用的次数永远是1次。
//这两步分别是什么意思呀??
FileOutputStream fw = new FileOutputStream(f);
pro.store(fw,"");// 这里是将pro集合中的数据以流的形式写到文件中去。
//希望这么说能给到帮组。
fr.close();
fw.close();
}
}
复制代码
作者:
陈振兴
时间:
2012-9-25 01:41
本帖最后由 陈振兴 于 2012-9-25 01:43 编辑
pro.setProperty("time", count+""); //因为property是以键值对的方式存储,属性列表中每个键及其对应值都是一个字符串。只要你调用setProperty方法,就会强制要求你写入的键、值都为字符串!
FileOutputStream fw = new FileOutputStream(f);
pro.store(fw,""); //针对你的属性列表写入输出字符,上面FileOutputStream就是一个输出流,不同一点就是这写入了Property指定的文件了,就相当于fw.writer(line)可以这样理解;
关于Hashtable:
1.Hashtable是Dictionary的子类,HashMap是Map接口的一个实现类;
2.Hashtable中的方法是同步的,而HashMap中的方法在缺省情况下是非同步的。即是说,在多线程应用程序中,不用专门的操作就安全地可以
使用Hashtable了;而对于HashMap,则需要额外的同步机制。但HashMap的同步问题可通过Collections的一个静态方法得到解决:
Map Collections.synchronizedMap(Map m)
这个方法返回一个同步的Map,这个Map封装了底层的HashMap的所有方法,使得底层的HashMap即使是在多线程的环境中也是安全的。
作者:
王贵朝
时间:
2012-9-25 06:47
pro.setProperty("time", count+""); //把操作完的time和count在重新设置到内存中
pro.store(fw,""); //从内存中持久化到文件
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2