Properties类继承于Hashtable类;
功能是将Hashtable类中的键值对保存到文件中,并可以从文件中读取;
什么情况下用呢?比如应用程序中设置的一些选项,确定后会将设置保存到文件中,以便下次打开设置不变。
Properties类实现文件存储时要求关键字和值都是String类型的。
常用函数:
store(OutputStream out,String header);//存入文件,参数是文件对象,标题信息。要异常处理,如果没有文件会自动产生文件
load(FileInputStream in);//从文件中读取,参数是文件对象,要异常处理。
getProperty(String key);//由关键字得到值,返回String类型。
setProperty(String key, String value);//存关键字和值,必须是String类型。
preoertyNames();获得所有的属性关键字,返回Enumeration对象,可以用来取出所有的属性。
习题:记录程序运行的次数并打印出来
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class TestPrperties {
public static void main(String [] args)
{
Properties p = new Properties();
try{
p.load(new FileInputStream("count.txt")) ;//从count.txt文件中读取到Properties里
}catch(Exception e)
{//发生异常时是首次读取,可能文件不存在,那么手动在p中存入0
p.setProperty("count",String.valueOf(0));
}
int c = Integer.parseInt(p.getProperty("count"))+1;//由关键字取出值,由String类型转为int
System.out.println("第" + c + "次运行");//打印第几次运行
//存入properties
p.setProperty("count", new Integer(c).toString());//转为String类型,存入p
try{
p.store(new FileOutputStream("count.txt"), "标题");//由p存入count.txt文件中
}
catch(Exception e)
{
e.printStackTrace();
}
}
}