用ClassLoader讀取資源文件

          關于讀取資源文件(如文本文件、圖像、二進制文件等),一般不推薦直接給出操作系統的路徑,而是給出相對于當前類的相對路徑,這樣就可以使用類的裝載器來裝載資源文件。常用的方法有:
          Class類的getResourceAsStream(String resourcePath);
          ClassLoader類的getResourceAsStream(String resourcePath)
          Class類的該方法最終還是委派給ClassLoader的getResourceAsStream方法,但是使用中發現Class#getResourceAsStream()使用的是絕對路徑(以/開頭),而ClassLoader#getResourceAsStream()使用的相對路徑。
          propterty文件經常放在類路徑的根路徑下(最頂層包的上層目錄,如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();
                  //輸出第一行內容
                  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

          統計

          常用鏈接

          留言簿(1)

          隨筆分類

          隨筆檔案

          最新隨筆

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 阿克陶县| 沐川县| 视频| 巢湖市| 砀山县| 客服| 鄂托克旗| 进贤县| 贵港市| 晴隆县| 贡嘎县| 陕西省| 布尔津县| 永嘉县| 辽宁省| 衡山县| 莒南县| 阳东县| 大田县| 杨浦区| 朝阳区| 汝南县| 张家港市| 东海县| 台北县| 阳朔县| 介休市| 龙川县| 西城区| 临澧县| 托克托县| 曲麻莱县| 社旗县| 潼南县| 定襄县| 奉化市| 宿州市| 滨州市| 湘阴县| 五莲县| 临沭县|