用ClassLoader讀取資源文件

          關于讀取資源文件(如文本文件、圖像、二進制文件等),一般不推薦直接給出操作系統(tǒng)的路徑,而是給出相對于當前類的相對路徑,這樣就可以使用類的裝載器來裝載資源文件。常用的方法有:
          Class類的getResourceAsStream(String resourcePath);
          ClassLoader類的getResourceAsStream(String resourcePath)
          Class類的該方法最終還是委派給ClassLoader的getResourceAsStream方法,但是使用中發(fā)現(xiàn)Class#getResourceAsStream()使用的是絕對路徑(以/開頭),而ClassLoader#getResourceAsStream()使用的相對路徑。
          propterty文件經(jīng)常放在類路徑的根路徑下(最頂層包的上層目錄,如classes),這樣加載property文件時就可以先用Class#getResourceAsStream方法獲取輸入源,再從該輸入源load各entry。
          code piece:
          package sinpo.usagedemo;

          import java.io.BufferedReader;
          import java.io.InputStream;
          import java.io.InputStreamReader;
          import java.util.Properties;

          import junit.framework.TestCase;

          /**
           @author 徐辛波(sinpo.xu@hotmail.com)
           * Oct 19, 2008
           */
          public class LoadResource extends TestCase {
              public void test() throws Exception {
                  //usage 1: use absolute path (mostly used)
                  InputStream in1 = this.getClass().getResourceAsStream("/sinpo/test2.properties");
                  //usage 2: use relative path
                  InputStream in2 = this.getClass().getClassLoader().getResourceAsStream("sinpo/test2.properties");
                  //usage 3: use system class path
                  InputStream in3 = ClassLoader.getSystemResourceAsStream("system.properties");
                  
                  //將讀取的資源作為Properties的輸入源
                  Properties props = new Properties();
                  props.load(in1);
                  String propValue = props.getProperty("propKey");
                  System.out.println(propValue);
                  
                  //將讀取的資源作為文本輸出
                  InputStreamReader reader = new InputStreamReader(in1);
                  BufferedReader bReader = new BufferedReader(reader);
                  String content = bReader.readLine();
                  //輸出第一行內(nèi)容
                  System.out.println(content);
                  
                  //TODO close them
              }
          }

          posted on 2008-10-19 20:36 徐辛波 閱讀(1273) 評論(0)  編輯  收藏 所屬分類: source pieces

          導航

          <2008年10月>
          2829301234
          567891011
          12131415161718
          19202122232425
          2627282930311
          2345678

          統(tǒng)計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          最新隨筆

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 罗定市| 镇康县| 靖远县| 璧山县| 西华县| 巴南区| 商水县| 汝州市| 逊克县| 富民县| 乐山市| 株洲县| 宿州市| 青神县| 石棉县| 天峻县| 海城市| 桃源县| 兴隆县| 远安县| 正宁县| 麦盖提县| 呼图壁县| 双鸭山市| 凤城市| 巴里| 北安市| 屏边| 麻栗坡县| 花垣县| 平顺县| 米泉市| 邵东县| 锡林浩特市| 什邡市| 吉安市| 那坡县| 焉耆| 阿拉尔市| 沛县| 德州市|