2012-03-12 116 views
2

此問題與this one有關。由於這是一個具體問題,我在這裏提出了這個問題。我曾嘗試創建一個文本文件,「foo.txt的」,一讀入我的活動做:在Android中從資產文件夾讀取文件時遇到問題

File file = new File("/assets/foo.txt"); 
if (file.exists()){ 
    txtView.setText("Exists"); 
} 
else{ 
    txtView.setText("Does not exist"); 
} 

的「foo.txt的」文件位於我的資產文件夾,我已經驗證了它存在於操作系統。我的TextView總是從上面的代碼中獲取文本「不存在」。我試圖去

File file = new File("/assets/foo.txt"); 
Scanner in = new Scanner(file); 

爲好,但是這會產生以下內嵌錯誤:「未處理的異常類型FileNotFoundException異常」。 Eclipse然後建議涉及try/catch,它可以消除錯誤,但是它也不能正常工作。

我也嘗試將我的資產文件夾設置爲「用作源文件夾」,但這沒有任何區別。我也嘗試使用原始文件夾,因爲幾個人建議不使用。我沒有選擇,真的需要幫助。應該很容易......

闖闖是去

AssetManager assetManager = getResources().getAssets(); 
InputStream is = assetManager.open("assets/foo.txt"); 

但是這將產生直列錯誤在第二行:「未處理的異常類型爲IOException」。

回答

12

我與CommonsWare在這種情況下(這是安全方面:)),但它應該是:

AssetManager assetManager = getResources().getAssets(); 
InputStream inputStream = null; 

    try { 
     inputStream = assetManager.open("foo.txt"); 
      if (inputStream != null) 
       Log.d(TAG, "It worked!"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

不要使用InputStream is = assetManager.open("assets/foo.txt");

+0

僅在使用「foo.txt」時仍會產生「未處理的異常類型IOException」。我可以選擇使用Eclipse中的try/catch來包圍它,但它沒有區別:( – 2012-03-12 21:29:27

+1

如果使用'this.getAssets()'而不是'getResources()。getAssets()'? – MByD 2012-03-12 21:34:44

+0

@ Krøllebølle - 也請清理並重建項目 – MByD 2012-03-13 05:50:34

2

您在運行時不使用File訪問assets/。您在運行時使用AssetManager訪問assets/,您可以通過getResources().getAssets()獲取該文件。

+0

我也嘗試過,抱歉沒有提及它。我已更新我的帖子。 – 2012-03-12 21:21:58

+0

@Krøllebølle:看到另一個答案 - 你需要擺脫路徑中的assets /'。 – CommonsWare 2012-03-12 21:26:49

2

試試這個:

private AssetManager am; 
    am=getAssets(); 

    InputStream inputStream = null ; 
     try 
     { 
      inputStream = am.open("read.txt"); 
     } 
     catch (IOException e) {} 
+0

與上面相同的錯誤:「未處理的異常類型IOException」 – 2012-03-12 21:32:56

+0

你可以粘貼我完整的文件像你的項目名稱/資產/文件名?? – 2012-03-12 21:44:02

+0

請參閱我的編輯解決方案 – 2012-03-12 21:45:44

相關問題