2013-12-24 70 views
1

我一直在尝试读取最近几天的文件,并尝试了下面的其他答案,但没有成功。这是我现在有导入文本文件中的代码:在Android SDK中导入文本文件

public ArrayList<String> crteDict() { 

    try { 
     BufferedReader br = new BufferedReader 
       (new FileReader("/program/res/raw/levels.txt")); 
     String line; 
     while ((line = br.readLine()) != null) { 
      String[] linewrds = line.split(" "); 
      words.add(linewrds[0].toLowerCase()); 
      // process the line. 
     } 
     br.close(); 


     } 
    catch (FileNotFoundException fe){ 
     fe.printStackTrace(); 

它是为了阅读文本文件,只需创建字的多头排列。它始终在FileNotFoundException中结束。 请让我知道任何答案。 谢谢!

回答

1

如果您的文件存储在Android项目的res/raw文件夹,您可以按如下读它,这个代码必须是Activity类中,如this.getResources()Context.getResources()

// The InputStream opens the resourceId and sends it to the buffer 
InputStream is = this.getResources().openRawResource(R.raw.levels); 
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

它不具有在一个Activity里面,因为你可以传递一个Context到任何方法。我建议你改变这个部分。我也会删除我的答案。 – ejohansson

+0

嗨感谢您的答复。它告诉我,getResource对于这种类型是未定义的。你知道我是如何解决这个问题的吗? – user3131169

+0

正如我上面提到的,'this'是指一个'Context'对象。你在哪里添加这个代码?使用' .this.getResources()'或'getContext()。getResources()'或者如果没有任何工作发布你的代码/给我更多的信息。最后,它的'getResources()'带's' –