2013-12-17 221 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()的文档。

相关问题