2013-12-17 53 views
2

,如果我使用輸入流像資產訪問文件夾

InputStream is = getAssets().open("errorMapperConfig.xml"); 

我得到NullPointerException從資產文件夾來訪問文件,幫我解決這個。

+0

我在java類的解析函數中使用這行代碼 –

+4

看起來'getAssets()'返回null。 – Steve

+0

您是否正確創建資產文件夾?看看我的答案在這裏:http://stackoverflow.com/a/20501733/1208581 – sulai

回答

0
private void readFiles() { 
      try 
      { 
      AssetManager assetManager = getAssets(); 
      InputStream inputStream; 
      inputStream = assetManager.open("webpages/how-to-use.html"); 

      String detail=loadTextFile(inputStream); 
      webView.loadData(detail, "text/html", "utf-8"); 

      } 
      catch(Exception e){ 
       Log.e("Exception ","======>"+e.toString()); 
      } 
     } 

    public String loadTextFile(InputStream inputStream) throws IOException { 
     ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 
     byte[] bytes = new byte[4096]; 
     int len = 0; 
     while ((len = inputStream.read(bytes)) > 0) 
      byteStream.write(bytes, 0, len); 
     return new String(byteStream.toByteArray(), "UTF8"); 
     } 

我希望這會有所幫助。謝謝!

1

使用Context變量getAssetes();

AssetManager mngr = myContext.getAssets(); 
InputStream is = mngr.open("errorMapperConfig.xml"); 
0

你將不得不主要活動的範圍內傳遞給這個類。把下面的代碼在類的與活動的onCreate()方法:

Context context = getApplicationContext(); 

然後,替換你的代碼TIH這樣的:

InputStream is = context.getAssets().open("errorMapperConfig.xml"); 

不要忘記,你必須有一個名爲errorMapperConfig.xml內部文件項目根目錄中名爲assets的文件夾。

請參閱getApplicationContext()的文檔。