getResourceAsStream和getResource的用法

          getResourceAsStream:查找具有給定名稱的資源。返回 InputStream

          getResource:查找帶有給定名稱的資源路徑。返回URL

          簡單示例:(注:任何一個類都有一個getClass()的方法)

          public class Test {
          ?public void getResource(String url){
          ??InputStream stream = getClass().getResourceAsStream(url);
          ??System.out.println(getClass().getResource(url));
          ??byte[] line = new byte[1024*1024];
          ??try {
          ???stream.read(line);
          ??} catch (IOException e) {
          ???// TODO Auto-generated catch block
          ???e.printStackTrace();
          ??}
          ??String str = new String(line);
          ??System.out.println(str.trim());
          ?}
          ?
          ?public static void main(String[] args) {
          ??new Test().getResource("/io/aaa.txt");
          ?}
          }
          運行結果:
          file:/D:/IBM/workspace/HtmlParser/io/aaa.txt
          abceefghijklmn
          第一行得到的是aaa.txt的路徑,第二行是aaa.txt的內容。
          需要注意的是必須有前面的“/”,代表的是工程目錄,否則找不到。

          posted on 2006-04-29 15:30 扭轉乾坤 閱讀(5207) 評論(1)  編輯  收藏 所屬分類: JAVA常用技巧

          評論

          # 不錯不錯 2008-08-15 09:54 goodlandscape

          看了例子總算明白資源的含義了  回復  更多評論   

          <2006年4月>
          2627282930311
          2345678
          9101112131415
          16171819202122
          23242526272829
          30123456

          導航

          統計

          常用鏈接

          留言簿(2)

          隨筆分類(31)

          隨筆檔案(30)

          文章分類(32)

          文章檔案(33)

          相冊

          PHP小站-首頁

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 闵行区| 晋中市| 新郑市| 镇巴县| 盐亭县| 武宁县| 阜新市| 安仁县| 卓尼县| 株洲市| 屏东县| 朝阳市| 漳浦县| 德昌县| 申扎县| 泾源县| 泽库县| 华坪县| 满城县| 大石桥市| 来安县| 黑龙江省| 罗田县| 鹤壁市| 泰来县| 隆尧县| 日土县| 郑州市| 绥化市| 尼木县| 汤阴县| 汉沽区| 儋州市| 深州市| 个旧市| 宁城县| 湘阴县| 永平县| 大名县| 绩溪县| 清远市|