Java属性类:Properties的常用方法

来源:互联网 发布:支付宝知托付 广告 编辑:程序博客网 时间:2024/06/05 02:57

 Properties类本身是Hashtable类的子类,也是按照key-value的形式存放数据的.

设置和取得属性:
public class PropertiesDemo01{public static void main(String args[]){Properties pro = new Properties() ;// 创建Properties对象pro.setProperty("BJ","BeiJing") ;// 设置属性pro.setProperty("TJ","TianJin") ;pro.setProperty("NJ","NanJing") ;System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;System.out.println("2、SC属性不存在:" + pro.getProperty("SC")) ;System.out.println("3、SC属性不存在,同时设置显示的默认值:" + pro.getProperty("SC","没有发现")) ;}};


将属性保存到普通的属性文件中:
public class PropertiesDemo02{public static void main(String args[]){Properties pro = new Properties() ;// 创建Properties对象pro.setProperty("BJ","BeiJing") ;// 设置属性pro.setProperty("TJ","TianJin") ;pro.setProperty("NJ","NanJing") ;File file = new File("D:" + File.separator + "area.properteis") ;// 指定要操作的文件try{pro.store(new FileOutputStream(file),"Area Info") ;// 保存属性到普通文件}catch(FileNotFoundException e){e.printStackTrace() ;}catch(IOException e){e.printStackTrace() ;}}};


从属性文件中读取内容:
public class PropertiesDemo03{public static void main(String args[]){Properties pro = new Properties() ;// 创建Properties对象File file = new File("D:" + File.separator + "area.properteis") ;// 指定要操作的文件try{pro.load(new FileInputStream(file)) ;// 读取属性文件}catch(FileNotFoundException e){e.printStackTrace() ;}catch(IOException e){e.printStackTrace() ;}System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;System.out.println("2、SH属性存在:" + pro.getProperty("SH")) ;}};


将属性保存在XML文件中:
public class PropertiesDemo04{public static void main(String args[]){Properties pro = new Properties() ;// 创建Properties对象pro.setProperty("BJ","BeiJing") ;// 设置属性pro.setProperty("TJ","TianJin") ;pro.setProperty("NJ","NanJing") ;File file = new File("D:" + File.separator + "area.xml") ;// 指定要操作的文件try{pro.storeToXML(new FileOutputStream(file),"Area Info") ;// 保存属性到普通文件}catch(FileNotFoundException e){e.printStackTrace() ;}catch(IOException e){e.printStackTrace() ;}}};


从XML文件中读取属性:
public class PropertiesDemo05{public static void main(String args[]){Properties pro = new Properties() ;// 创建Properties对象File file = new File("D:" + File.separator + "area.xml") ;// 指定要操作的文件try{pro.loadFromXML(new FileInputStream(file)) ;// 读取属性文件}catch(FileNotFoundException e){e.printStackTrace() ;}catch(IOException e){e.printStackTrace() ;}System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;}};






3 0