java從類路徑下載入資源檔__java從類路徑下載入資源檔

來源:互聯網
上載者:User

java的世界離不開資源設定檔,像spring架構等都非常依賴資源設定檔,而且spring也封裝了resource類,來處理資源檔的載入,這裡就不仔細分析spring載入資源檔了,主要分析下java 的ResourceBundle類載入資源設定檔。

      其實分析了一下這個類的實現,其原理和spring一樣,都是利用ClassLoader讀取系統資源(SystemResource)檔案。


  ResourceBundle bundle = ResourceBundle.getBundle(propFile, Locale.ENGLISH);

這個是統一的資源載入方式,屬性檔案的載入由

 System.out.println(bundle.getClass());// class java.util.PropertyResourceBundle


java.util.PropertyResourceBundle這個實作類別實現的,這個實作類別主要讀取資源(從指定檔案),負載檔案到

java.util.Properties。

讀取負載檔案內容的關鍵代碼:

 @SuppressWarnings({"unchecked", "rawtypes"})    public PropertyResourceBundle (InputStream stream) throws IOException {        Properties properties = new Properties();        properties.load(stream);        lookup = new HashMap(properties);    }


@SuppressWarnings({"unchecked", "rawtypes"})    public PropertyResourceBundle (Reader reader) throws IOException {        Properties properties = new Properties();        properties.load(reader);        lookup = new HashMap(properties);    }


不過定位資源檔的操作還是要看抽象類別ResourceBundle的代碼:

/**     * A wrapper of ClassLoader.getSystemClassLoader().     */    private static class RBClassLoader extends ClassLoader {        private static final RBClassLoader INSTANCE = AccessController.doPrivileged(                    new PrivilegedAction<RBClassLoader>() {                        public RBClassLoader run() {                            return new RBClassLoader();                        }                    });        private static final ClassLoader loader = ClassLoader.getSystemClassLoader();        private RBClassLoader() {        }        public Class<?> loadClass(String name) throws ClassNotFoundException {            if (loader != null) {                return loader.loadClass(name);            }            return Class.forName(name);        }        public URL getResource(String name) {            if (loader != null) {                return loader.getResource(name);            }            return ClassLoader.getSystemResource(name);        }        public InputStream getResourceAsStream(String name) {            if (loader != null) {                return loader.getResourceAsStream(name);            }            return ClassLoader.getSystemResourceAsStream(name);        }    }

定位資源檔載入資源的關鍵是
getResource
<pre name="code" class="java">getResourceAsStream
 這些方法。 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.