2016-05-14 131 views
1

我知道这个主题可能已经被覆盖,但我无法找到我的问题的答案。
我有一个文件,其中包含我需要阅读的一些词。
它在我的桌面版本上正常工作,但我尝试在模拟器上运行,我得到java.io.FileNotFoundException - no file found
我知道我必须以不同于桌面的方式加载文件。读一个纯文本文件

任何帮助,将不胜感激。

这里是读取文件的代码。

String line; 

     try { 

      BufferedReader br = new BufferedReader(new FileReader("words.txt")); 
      if (!br.ready()) { 
       throw new IOException(); 
      } 
      while ((line = br.readLine()) != null) { 
       words.add(line); 
      } 
      br.close(); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 

但这不适用于Android!

仍然没有解决方案!

+0

“但是,这并不在Android上工作!” - 这是因为'words.txt'是一个无效的路径。这个文件到底在哪里? – CommonsWare

+0

在我的assests文件夹..我也试过“assests/words.txt”和“/assests/words.txt” – Joe

+0

http://stackoverflow.com/questions/4081763/access-resource-files-in-android –

回答

1

您可以在android中从上下文访问文件。

Context Context; 
AssetManager mngr = context.getAssets(); 
String line; 
     try { 

      BufferedReader br = new BufferedReader(new FileReader(mngr.open("words.txt"))); 
      if (!br.ready()) { 
       throw new IOException(); 
      } 
      while ((line = br.readLine()) != null) { 
       words.add(line); 
      } 
      br.close(); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 

或者试试这个:

String line; 
     try { 

      BufferedReader br = new BufferedReader(new FileReader(getApplicationContext().getAssets().open("words.txt"))); 
      if (!br.ready()) { 
       throw new IOException(); 
      } 
      while ((line = br.readLine()) != null) { 
       words.add(line); 
      } 
      br.close(); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 
+0

上下文=无法解析符号?我在做什么错误 – Joe

+0

也验证您的资产文件夹在正确的目录:'app/src/main/assets /' – user6158055

+0

他们都给我同样的东西不能解决符号.. – Joe

1

资产是开发机器上的文件。它们不是设备上的文件。

获得资产InputStreamuse open() on an AssetManager。在ActivityService或其他Context上拨打getAssets()即可获得AssetManager