转自http://blog.chinaunix.net/u1/36711/showart_479048.html
Properties类是Hashtable类的子类,Properties类将Hashtable中的关键字和值保存到文件中,还可以从文件中读取关键字和值到Hashtable的对象中。在什么情况下要使用Properties类呢?大多数程序都有功能设置的选项,例如firefox的设置选项,假如我们要修改一些设置,在点击确定后,这些设置就会存入一个配置文件当中。当firefox重新启动后,这些设置值就会起作用了。如果调用Properties类中的store方法就是将Properties中的关键字和值的信息存储到文件当中,要注意这个关键字和值都必须是String对象类型的。下面举一个例子说明:使用Properties把程序的启动运行次数记录在某个文件当中,每次运行就打印出它的运行次数。
import java.util.*;import java.io.*;public class TestProperties { public static void main(String[] args) { Properties p = new Properties();//Properties类是Hashtable类的一个子类 try { p.load(new FileInputStream("count.txt"));//从一个文件对象中装载进来 } catch(Exception e) { p.setProperty("count",String.valueOf(0));//setProperty方法里面的参数必须为String类型 } //int i = Integer.parseInt(p.get("count")); //get方法是从Hashtable类中继承下来的,里面的参数可以是任意类型 int i = Integer.parseInt(p.getProperty("count"));//用getProperty方法直接就是String类型的了 System.out.println("运行了"+i+"次运行"); i++; //p.put("count",new Integer(i).toString());//put方法是从Hashtable类中继承下来的,里面的参数可以是任意类型 p.setProperty("count",new Integer(i).toString());//用setProperty方法直接就是String类型的了 try { p.store(new FileOutputStream("count.txt"),"program is used: "); } catch(Exception e) { e.printStackTrace(); } }}
阅读全文(3098) | 回复(0) | 编辑 | 精华
|