【Java類集】_屬性類:Properties筆記
本章目標:
掌握Properties類的使用
可以向普通及XML格式的檔案中儲存及讀取屬性
在類集中提供了一個專門的Properties類,以完成屬性的操作。
public class Properties extends Hashtable<Object,Object>
Properties是Hashtable的子類,則也是Map的子類,可以使用Map的全部操作,但是一般情況下屬性類是單獨使用的。
設定屬性:
public Object setProperty(String key,String value)
得到屬性:
public String getProperty(String key)
public String getProperty(String key,String defaultValue)
驗證以上的操作方法:
import java.util.Properties;public class PropertiesDemo01{ public static void main(String args[]){ Properties pro = new Properties();//建立Properties類 pro.setProperty("BJ","BeiJing"); pro.setProperty("TJ","TianJing"); 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","沒有發現")); }}
屬性操作中以上屬於設定和讀取屬性,當然,對於屬性中可以將屬性儲存在檔案之中,提供了以下的方法:
將以下屬性寫入到D:\area.properties檔案之中。
import java.util.Properties;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;public class PropertiesDemo02{ public static void main(String args[]){ Properties pro = new Properties();//建立Properties類 pro.setProperty("BJ","BeiJing"); pro.setProperty("TJ","TianJing"); pro.setProperty("NJ","NanJing"); File file = new File("D:"+File.separator+"area.properties");//指定要操作的檔案 try{ pro.store(new FileOutputStream(file),"Area Info");//儲存屬性到指定檔案 }catch(IOException e){ e.printStackTrace(); } }}
讀取properties檔案
public void load(InputStream inStream) throws IOException
import java.util.Properties;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class PropertiesDemo03{ public static void main(String args[]){ Properties pro = new Properties(); File file = new File("D:"+File.separator+"area.properties");//指定要操作的檔案 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")); }}
以上是全部儲存在了普通的檔案之中,實際上在Properties操作的時候也可以將內容全部儲存在XML檔案之中。
import java.util.Properties;import java.io.File;import java.io.FileOutputStream;import java.io.FileNotFoundException;import java.io.IOException;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() ; } }};
總結:
1、如果進一步瞭解屬性操作,則可以繼續學習後續的反射機制部分,瞭解屬性類的應用。
2、屬性中的類型肯定都是字串,因為操作最方便。
3、屬性可以向普通檔案或XML檔案中儲存或讀取,按照指定格式可以向檔案中任意擴充屬性。