2012-03-24 58 views

回答

19

看看我的答案here來看看如何從POJO讀取文件。

通常,res文件夾應該通過ADT插件自動添加到項目構建路徑中。假設你有下RES /原始文件夾中存儲的test.txt,而不android.content.Context閱讀:

String file = "raw/test.txt"; // res/raw/test.txt also work. 
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file); 

我有一個老版本的SDK之前這樣做,它應該與最新的SDK正常工作。嘗試一下,看看這是否有幫助。

+0

感謝您的提示。我剛剛嘗試過。 Eclipse不喜歡將文件放在res下,所以我讓文件保留在res \ raw中。 getClassLoader()。getResourceAsStream(「text.txt」)或this.getClass()。getClassLoader()。getResourceAsStream(「raw \ text.txt」) – Hong 2012-03-24 21:55:12

+1

@Hong,我在我的Mac上使用SDK r16嘗試過,現在我可以確認「res/raw/test.txt」和「raw/test.txt」。而「test.txt」會拋出NPE。請注意,您需要斜槓(/),而不是反斜槓(\\)。 – yorkw 2012-03-24 22:21:04

+0

是的!有用!它也在靜態構造函數中工作,以便每次調用該方法時都不必執行此類讀取。非常感謝。 – Hong 2012-03-24 22:31:23

3

爲了訪問資源,你需要一個上下文。請參閱developer.android站點上的Context.class的定義

有關應用程序環境的全局信息的接口。這個 是一個抽象類,其實現由Android 系統提供。它允許訪問特定應用的資源和 類,以及向上調用應用程序級的操作,如 開展活動,廣播和接收意圖等

因此,通過上下文可以訪問一個資源文件。您可以創建另一個類並將活動的上下文傳遞給它。創建一個讀取指定資源文件的方法。

例如:

public class ReadRawFile { 
    //Private Variable 
    private Context mContext; 

    /** 
    * 
    * Default Constructor 
    * 
    * @param context activity's context 
    */ 
    public ReadRawFile(Context context){ 
     this.mContext = context; 
    } 

    /** 
    * 
    * @param str input stream used from readRawResource function 
    * @param x integer used for reading input stream 
    * @param bo output stream 
    */ 
    private void writeBuffer(InputStream str, int x, ByteArrayOutputStream bo){ 
     //not hitting end 
     while(x!=-1){ 
      //write to output buffer 
      bo.write(x); 
      try { 
       //read next 
       x = str.read(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    /** 
    * 
    * @return output file to string 
    */ 
    public String readRawResource(){ 
     //declare variables 
     InputStream rawUniversities = mContext.getResources().openRawResource(R.raw.universities); 
     ByteArrayOutputStream bt = new ByteArrayOutputStream(); 
     int universityInteger; 

     try{ 
      //read/write 
      universityInteger = rawUniversities.read(); 
      writeBuffer(rawUniversities, universityInteger, bt); 

     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
     //return string format of file 
     return bt.toString(); 
    } 

} 
+0

感謝您的回覆。根據我對您答案的理解,沒有上下文的情況下無法閱讀原始文本。 – Hong 2012-03-24 20:55:35

+1

是的,你需要一個上下文來讀取資源文件。 – Radu 2012-03-24 20:56:26

相關問題