2016-05-14 58 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