Java中resourceBundle和Properties的區別

來源:互聯網
上載者:User

標籤:

第一種辦法
InputStream is = Test.class.getResourceAsStream("DbConfig.properties");
Properties p = new Properties();
p.load(is);
System.out.println(p.get("jndi"));
Test.class要放在DbConfig.properties同一目錄??? 這句話需要待測試.
第二種辦法
private String BUNDLE_NAME = "com.newland.alarmquery.resource.DbConfig";///不要加上副檔名
ResourceBundle resource_bundle = ResourceBundle.getBundle(BUNDLE_NAME);
jndi=resource_bundle.getString("jndi");
System.out.println(p.get("jndi"));
一般來說,ResourceBundle類通常是用於針對不同的語言來使用的屬性檔案。
而如果你的應用程式中的屬性檔案只是一些配置,並不是針對多國語言的目的。那麼使用Properties類就可以了。
通常可以把這些屬性檔案放在某個jar檔案中。然後,通過調用class的getResourceAsStream方法,來獲得該屬性檔案的流對象,再用Properties類的load方法來裝載。
有時候有些簡單的設定檔可以沒必要使用xml,其實ResourceBundle類就已經做的很好的。它甚至可以搜尋到classpath裡的jar檔案中一些properties檔案。
例如在jar檔案中的根目錄放置一個檔案:DbConfig.properties,然後只要這個jar檔案在classpath裡。就可以使用這樣的語句來獲得一些屬性

【需要注意的地方:】
1.ResourceBundle.getBundle(String arg0)中的參數arg0必須包含屬性檔案的完整路徑。
2.將屬性檔案(例如config.properties)和讀取檔案在一起;
屬性檔案和讀取的檔案要放在一起,如果要分開這兩個檔案呢?那麼我們自己可以自己建立一個目錄,將屬性檔案放到其下,再將該目錄設定為classloader載入的目錄(加入類路徑中)則可,如下:
1、在項目下建一檔案夾,路徑隨意,名字任意(這為:properties)。
2、(Eclipse中)選擇項目->Properties->java Build Path->Libraries->Add
Class Folder,將properties檔案加入類路徑即可(或者手動在.classpath檔案中加入:<classpathentry kind="lib" path="properties"/>)。然後直接用
ResourceBundle.getBundle("config");則可讀取
properties/config.properties檔案的內容。
3.resourceBundle.getBundle(args0)中傳入的參數為資源檔的basename.且不用加.properties檔案尾碼。
如資源檔名為:myres_zh_CN.properties或myres.properties則只需要傳入myres就可以 了。
4.ResourceBundle這個類的作用就是讀取資源屬性檔案(properties),然後根據.properties檔案的名稱資訊(本地化資訊),匹配當前系統的國別語言資訊(也可以程式指定),然後擷取相應的properties檔案的內容。

Java中resourceBundle和Properties的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.