淺析類加載器的方式管理資源和配置文件

資源文件resource通常的加載方式,用類加載器的方式管理資源和配置文件;

示例要用到的文件:
資源文件:config.properties 裏面只有一行語句:
className=java.util.ArrayList
java
代碼
:
package com.itsoft;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

public class ReflectFrame {

public static void main(String[] args) throws Exception {
    InputStream ipStream = new FileInputStream("config.properties");
    Properties props = new Properties();
    props.load(ipStream);
    ipStream.close();
    String className = props.getProperty("className");//

    Collection collection = (Collection) Class.forName(className).newInstance();
    collection.add("
框架反射
");
    collection.add("
資源文件
");
    collection.add("
類加載器
");
    System.out.println(className);//
輸出:
java.util.ArrayList
    System.out.println(collection);//
輸出:[框架反射, 資源文件, 類加載器
]
}
}

分析:上述代碼用想運行不出錯,那麼config.properties必須放到工程根目錄下面,此時它是一個相對路徑,
但是我們發佈程序時,會發現,工程根目錄下面的這個配置文件是不會發布到tomcat中的,所以實際應用中,
這種做法是不可取的。

針對上述問題,有如下解決方法:
1.
使用絕對路徑:如: InputStream ipStream = new FileInputStream("F:\\workspace\\webtest\\config.properties");
注:如果要應用這種絕對路徑的方法,那麼一定要記住用完整的路徑不是硬編碼,而是運算出來的。

2.使用類加載器:
原理:我們知道,每一個class文件運行的時候都必須加載到內存中,這個功能由類加載器來提供,
既然class文件它可以加載,那麼其他資源文件,當然也可以由它來加載。
類加載器加載的時候,當然是從classpath的根目錄路徑下開始尋找並加載文件;

1)我們把config.properties文件和ReflectFrame.java放在同一目錄下時:
   InputStream ipStream = ReflectFrame.class.getClassLoader().getResourceAsStream("com/itsoft/config.properties");
注意:這樣用法相對於classpath,所以com/itsoft/config.properties前面不需要多餘的在加一個"/";這種方式的過程就是首先
找到ReflectFrame這個類,然後通過該類找到它的加載器,再由類加載器去加載資源文件,那麼我們能不能找到一個更直接的方法
又這個類去找到相關的資源文件呢?當然可以,看下面的例子,類加載器的簡化形式;

2)config.properties文件和ReflectFrame.java依舊位於同一目錄下:
InputStream ipStream = ReflectFrame.class.getResourceAsStream("config.properties");
注:這種做法此時用的是相對路徑的形式,它是相對於class本身的;

3)config.properties位於com.itsoft.resource包下時:
InputStream ipStream = ReflectFrame.class.getResourceAsStream("resource/config.properties");
注:同2,這種做法此時用的是相對路徑的形式,它是相對於class本身的;

4)config.properties位於com.itsoft.resource包下時:
InputStream ipStream = ReflectFrame.class.getResourceAsStream("/com/itsoft/resource/config.properties");
注:它也可以用絕對路徑

小結:
1.
IO流的方式讀寫文件,通常是用絕對路徑,但是爲了通用性,這個絕對路徑通常不要硬編碼,而是運算出來的。
2.
類加載器在各種框架中普遍應用,無論是直接的加載(1),還是簡化的加載(234),它們的本質都是ClassLoader
3.
簡化的類加載器可以使用相對路徑,也可以使用絕對路徑。


代碼(當資源文件位於不同的位置時的寫法)
   //InputStream ipStream = new FileInputStream("F:\\workspace\\webtest\\config.properties");
   //InputStream ipStream = new FileInputStream("config.properties");
   //InputStream ipStream = ReflectFrame.class.getClassLoader().getResourceAsStream("com/itsoft/config.properties");
   //InputStream ipStream = ReflectFrame.class.getResourceAsStream("config.properties");
   //InputStream ipStream = ReflectFrame.class.getResourceAsStream("resource/config.properties");
   //InputStream ipStream = ReflectFrame.class.getResourceAsStream("/com/itsoft/resource/config.properties");

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章