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")) ;
}
};