Properties檔案的解析
阿新 • • 發佈:2019-01-10
因為在配置框架時要對配置檔案進行讀取,因此簡單瞭解了一下,僅供參考
一、介紹
Properties檔案在Java中主要為配置檔案,檔案型別為:.properties,格式為文字檔案,內容格式為"鍵=值"
二、讀取
這裡我採用的是getResourceAsStream的檔案讀取方法
如果想要使用這個方法,則需要了解一些基本使用資訊:
1、讀取檔案路徑範圍:只侷限於工程的原始檔中
2、檔案訪問形式:帶"/"是絕對路徑,不帶"/"是相對路徑
3、讀取檔案型別:主要為:.properties檔案,.xml檔案
三、使用
主要方法有:
1、 load ( InputStream inStream) :從輸入流中讀取屬性列表(鍵和元素對)。通過對指定的檔案(比如的 beans.properties 檔案)進行裝載來獲取該文
件中的所有鍵 - 值對。
2、 setProperty ( String key, String value) :呼叫 Hashtable 的方法 put 。他通過呼叫基類的put方法來設定 鍵 - 值對。
3、 getProperty ( String key) :用指定的鍵在此屬性列表中搜索屬性。也就是通過引數 key ,得到 key 所對應的 value。
4、 store ( OutputStream out, String comments) :以適合使用 load 方法載入到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素
對)寫入輸出流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的檔案中去。
5、 clear ():清除所有裝載的 鍵 - 值對。該方法在基類中提供。
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; public class Pros { public static void main(String[] args) throws IOException { InputStream is = Pros.class.getResourceAsStream("beans.properties"); OutputStream os = new FileOutputStream("src/com/jiang/properties/beans.properties"); Properties ps = new Properties(); //讀取檔案 ps.load(is); //檢視檔案中指定鍵的值 String p = ps.getProperty("sanguo"); System.out.println(p); //給指定檔案中寫入資料 ps.setProperty("hong", "kong"); ps.store(os, "Update"+"xiyouji"+"name"); } }