2017-10-08 100 views
1

我得到除了當我嘗試打開res/raw文件夾中的文件。Android開發,原始資源無法找到

InputStream in = Resources.getSystem().openRawResource(R.raw.eng_sample); 

唯一的例外是:

android.content.res.Resources$NotFoundException: Resource ID #0X89890 

我可以看到該文件eng_sample.txt在APK中res/raw/eng_sample.txt

最重要的是,當我做R.raw.並按Ctrl-space文件eng_sample作爲建議給出。

然後是什麼問題?我該如何解決?

非常感謝提前。

P.S.

我也嘗試把文件eng_sample.txt納入main/assets。然後提取文件與

InputStream in = context.getAssets().open("file:///android_asset/eng_sample.txt 

但現在我得到一個IO異常。

也許有人可以告訴我如何使這種方法工作,而不是上面的那個?

回答

1

Resources.getSystem()返回共享全局資源對象,該對象僅提供對系統資源(無應用程序資源)的訪問。

另外context.getAssets().open(fileName/*not path*/)用於從資產目錄中獲取文件,您應該只提供文件名,而不是整個路徑。

要從原始文件打開流,使用方法:

context.getResources().openRawResource(R.raw.eng_sample); 
1

我一直在使用同樣的目的該代碼。你可以做這樣的事情

BufferedReader mReader = null; 
try { 
     mReader = new BufferedReader(
    new InputStreamReader(getAssets().open("eng_sample.txt"))); 
String mLine; 
while ((mLine = mReader.readLine()) != null) { 
     //do your stuff with line 
     ... 
    } 
    } catch (IOException e) { 
    //print stack trace 
    } finally { 
    if (mReader != null) { 
      try { 
        mReader.close(); 
       } catch (IOException e) { 
       //print stack trace 
      } 
     } 
    } 

希望它有幫助。