android讀取資源文件的方法

方法一:把目標文件放入resources文件中,以通過讀取R的資源文件來獲取,具體方式如下:

       1、在res下新建raw文件,將帶讀取文件添加到raw文件目錄下。
   
       2、添加如下代碼:
  1. // 如果要使用文件名獲取文件數據:首先獲取資源id然後再通過id獲取輸入流
  2.         /** String fileName = fileName;
  3.    String packetName = context.getPackageName();
  4.    //將fileName 轉換成id 
  5.    int resId = context.getResources().getIdentifier(fileName, "raw", packetName);
  6.    ObjectInputStream ois = null;
  7.    InputStream im = context.getResources().openRawResource(resId); 
  8.         //其中getIdentifier三參數分別是:文件名,資源所在文件夾名(如:drawable, raw,),包路徑 

  9.         */


  10.         InputStream im = getResources().openRawResource(R.raw.h_data11);
  11.         BufferedReader read = new BufferedReader(new InputStreamReader(im));
  12.         String line = "";
  13.         StringBuilder sb = new StringBuilder();
  14.         try {
  15.             while((line = read.readLine()) != null) {
  16.                 sb.append(line).append("\n");
  17.             }
  18.         } catch (IOException e) {
  19.             e.printStackTrace();
  20.         } finally {
  21.             if(read != null) {
  22.                 try {
  23.                     read.close();
  24.                     read = null;
  25.                 } catch (IOException e) {
  26.                     e.printStackTrace();
  27.                 }
  28.             }
  29.             
  30.             if(im != null) {
  31.                 try {
  32.                     im.close();
  33.                     im = null;
  34.                 } catch (IOException e) {
  35.                     e.printStackTrace();
  36.                 }
  37.             }
  38.         }
  39.         Log.v("", "result = " + sb.toString());
複製代碼
方法二:使用assets 只讀文件進行讀取。

        1、將文件copy到assets下,可以新建文件夾如:“www”然後將文件放入www文件夾中,讀取的path爲:"www/filename"
  1. String result = "";
  2.   
  3.   ObjectInputStream ois = null;
  4.   AssetManager am = context.getResources().getAssets();
  5.   try {
  6.       ois = new ObjectInputStream(am.open("www/filename"));
  7.       result = (String) ois.readObject();
  8.   } catch (StreamCorruptedException e) {
  9.       e.printStackTrace();
  10.   } catch (FileNotFoundException e) {
  11.       e.printStackTrace();
  12.   } catch (IOException e) {
  13.       e.printStackTrace();
  14.   } catch (ClassNotFoundException e) {
  15.       e.printStackTrace();
  16.   } finally {
  17.    try {
  18.     if (ois != null) {
  19.      ois.close();
  20.      ois = null;
  21.     }
  22.    } catch (IOException e) {
  23.     e.printStackTrace();
  24.    }
  25.   }
複製代碼
以對象的方式讀取文件中的數據,如果沒有新建文件夾,把前面的“www/”去掉就ok啦
發佈了13 篇原創文章 · 獲贊 6 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章