java 資源檔,資源檔
1. 概述
資源檔也叫屬性檔案,指properties 檔案,這種檔案以key=value格式儲存內容,代碼中可以使用Properties 類來讀取這個檔案。String value=p.getProperty(key);就能得到對應的資料。一般這個檔案作為一些參數的儲存,代碼就可以靈活一點用於適應多語言環境,隨著系統的語言環境的變化,讀取不同的屬性檔案,複雜點可以用xml 做配置。通俗點講,就相當於定義一個檔案,在這個檔案裡面定義一些變數的值,在程式裡面可以調用這些變數。好處就是,如果程式中的參數值需要變動,直接來改這個.property 檔案就可以了,不用再去修改原始碼。優點在於有利於你以後的代碼重構。
2. 資源檔的建立方法
在 IDE 裡建立一個file 尾碼改為.properties,就建立了一個屬性檔案。
3. 資源檔的結構
屬性檔案(資源檔)結構:
test1=aaa
test2=bbb
樣本:
driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=books
user=sa
password=120010
4. 資源檔的讀取
讀取.properties 檔案的步驟如下:
建立繼承自Properties 的類,並以單例模式獲得執行個體:私人的靜態成員,私人的預設構造方法,公有的靜態同步方法。
使用Class 對象的getResourceAsStream()方法,把指定的屬性檔案讀入輸入資料流中,並使用Properties 類中的load()方法,從輸入資料流中讀取屬性列表(鍵/值對)。
樣本:
建立的.properties檔案為
jdbc.driver_class=org.gjt.mm.mysql.Driverjdbc.connection.url=jdbc\:mysql\://localhost\:3306/stumegjdbc.connection.username=rootjdbc.connection.password=1234
建立讀取設定檔工具類:
public class ConfigManager{private static ConfigManager configManager;//聲明configManager對象private static Properties properties;//聲明properties對象private ConfigManager(){//無參構造方法//擷取設定檔儲存路徑String configFile = "database.properties";//建立properties對象properties = new Properties();//建立流擷取設定檔內容InputStream in = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);try {//調用load方法properties.load(in);} catch (IOException e) {e.printStackTrace();}}//建立單例模式public static ConfigManager getInstance(){if(configManager==null){configManager = new ConfigManager();}return configManager;}public String getString (String key){return properties.getProperty(key);}}
然後再需要用到地方調用
// 讀出配置資訊String driver=ConfigManager.getInstance().getString("jdbc.driver_class");String url=ConfigManager.getInstance().getString("jdbc.connection.url");String username=ConfigManager.getInstance().getString("jdbc.connection.username");String password=ConfigManager.getInstance().getString("jdbc.connection.password");
java資源檔
屬性檔案指properties檔案
在IDE裡建立一個file尾碼改為.properties就建立了一個屬性檔案
屬性檔案結構:
test1=aaa
test2=bbb
Ps:中文的話請使用unicode表示
有很多種讀取屬性檔案的方式,我舉例其中的一種:
//構造器內的路徑為src檔案夾下的*.properties檔案
//假設在src檔案夾下放置了屬性檔案a.properties
ResourceBundle rb = ResourceBundle.getBundle("a");
String str = rb.getString("test1");
此時str的值為屬性檔案中test1對應的值
java中什是資源檔?
在你的代碼裡調用了一些資源檔,片,音樂等
參考資料:www.enet.com.cn/....shtml