java 讀取和更改properties

// 讀
	public String readPeopleNumber(){
		String peopleNumber="";
		Properties prop = new Properties();
        try{
            //讀取屬性文件tuancheData.properties
        	String path = ServletActionContext.getRequest().getRealPath("/data/tuancheData.properties");
            InputStream in = new BufferedInputStream (new FileInputStream(path));
            prop.load(in);     ///加載屬性列表
            Iterator<String> it=prop.stringPropertyNames().iterator();
            while(it.hasNext()){
                String key=it.next();
                System.out.println(key+":"+prop.getProperty(key));
                peopleNumber = prop.getProperty(key);
            }
            
            in.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
		return peopleNumber;
	}
	// 寫
	public void writePeopleNumber(String number) throws Exception{
		Properties prop = new Properties();// 屬性集合對象 
		String path = ServletActionContext.getRequest().getRealPath("/data/tuancheData.properties");
//		FileInputStream fis = new FileInputStream(path);// 屬性文件輸入流 
//		prop.load(fis);// 將屬性文件流裝載到Properties對象中 
//		fis.close();// 關閉流 

		// 獲取屬性值,sitename已在文件中定義 
//		System.out.println("獲取屬性值:peopleNumber=" + prop.getProperty("peopleNumber")); 
		// 獲取屬性值,country未在文件中定義,將在此程序中返回一個默認值,但並不修改屬性文件 
		// System.out.println("獲取屬性值:country=" + prop.getProperty("country", "中國")); 

		// 修改sitename的屬性值 
		prop.setProperty("peopleNumber", number); 
		// 文件輸出流 
		FileOutputStream fos = new FileOutputStream(path); 
		// 將Properties集合保存到流中 
		prop.store(fos, "Copyright (c) Boxcode Studio"); 
		fos.close();// 關閉流 
//		System.out.println("獲取修改後的屬性值:peopleNumber=" + prop.getProperty("peopleNumber")); 
		
	}
相關文章
相關標籤/搜索