2010-11-02 108 views
25

我在我的/ res/raw /文件夾(/res/raw/textfile.txt)中有一個資源文件,我試圖從我的android應用程序讀取進行處理。訪問Android中的資源文件

public static void main(String[] args) { 

    File file = new File("res/raw/textfile.txt"); 

    FileInputStream fis = null; 
    BufferedInputStream bis = null; 
    DataInputStream dis = null; 

    try { 
     fis = new FileInputStream(file); 
     bis = new BufferedInputStream(fis); 
     dis = new DataInputStream(bis); 

     while (dis.available() != 0) { 
       // Do something with file 
      Log.d("GAME", dis.readLine()); 
     } 

     fis.close(); 
     bis.close(); 
     dis.close(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

我已經嘗試了不同的路徑語法,但總是得到java.io.FileNotFoundException錯誤。我如何訪問/res/raw/textfile.txt進行處理?是文件文件=新文件(「res/raw/textfile.txt」); Android中的錯誤方法?


*答:*

// Call the LoadText method and pass it the resourceId 
LoadText(R.raw.textfile); 

public void LoadText(int resourceId) { 
    // The InputStream opens the resourceId and sends it to the buffer 
    InputStream is = this.getResources().openRawResource(resourceId); 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
    String readLine = null; 

    try { 
     // While the BufferedReader readLine is not null 
     while ((readLine = br.readLine()) != null) { 
     Log.d("TEXT", readLine); 
    } 

    // Close the InputStream and BufferedReader 
    is.close(); 
    br.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

考慮我們[Apache Commons](http://commons.apache.org/proper/commons-io/)。在那裏搜索'IOUtils'。 – JJD 2013-10-08 14:39:55

回答

23

如果你從你的活動/控件調用在res/raw/textfile.txt文件:

getResources().openRawResource(...)返回InputStream

的點實際上應的整數R.raw發現...對應的文件名,可能R.raw.textfile(它通常是沒有擴展名的文件的名稱)

new BufferedInputStream(getResources().openRawResource(...));然後讀取該文件的內容作爲流

+0

我試過了:File file = new File(R.raw.textfile); - 我會嘗試使用getResources()。OpenRawResource(R.raw.textfile)並將其提供給File,如果可以的話。 – Selzier 2010-11-02 21:25:27

+0

無論我如何使用「getResources()。openRawResource(R.raw.textfile)」eclipse總是給出錯誤「方法getResources()未定義類型MyClass」。 – Selzier 2010-11-02 22:04:58

+0

getResources()是Context類的一個方法。您只能獲取關於上下文的資源。 – Falmarri 2010-11-02 22:20:45

10

只是一個事實,即你有這樣的public static void main(String[] args)意味着你實現你的代碼極其錯誤的。你幾乎可以肯定沒有經過任何hello android教程。你絕對應該這樣做。

+1

+1好抓!有趣的看到一個Android應用程序的主要方法XD – Cristian 2010-11-02 20:30:33

+0

我已經通過所有你好的android教程,包括視圖教程,錯誤日誌教程和記事本教程的每一個。我不是Java專家,但不明白爲什麼使用public static void main(String [] args)是錯誤的。 – Selzier 2010-11-02 21:20:40

+2

,因爲這不是Android運行應用程序的方式。現在,你可以包含這個,也許是爲了運行你自己的測試或者什麼(爲什麼不呢?),但是在Android世界中,你的程序永遠不可能控制。當某個事件發生時(例如用戶按下按鈕時),將調用應用程序中相應的回調方法。當你的回調完成後,控制權返回到Android。 – 2012-04-07 18:14:19