2010-11-02 104 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