Android之读取Resource和Assets中的文件

public String getFromRes(String FileName){
     String result = "";
     try{
      InputStream in = getResources().openRawResource(R.raw.test2);//获取资源
      int length = in.available();//获取文字字数
      byte[]buffer = new byte[length];
      in.read(buffer);//读到数组中
            //设置编码
      result = EncodingUtils.getString(buffer, "UTF-8");
     }catch (Exception e) {
  }
  return result;
    }
    public String getFromAssets(String FileName){
     String result = "";
     try{
      InputStream in = getAssets().open(FileName);//获取资源
      int length = in.available();//获取文字字数
      byte[]buffer = new byte[length];
      in.read(buffer);//读到数组中
            //设置编码
      result = EncodingUtils.getString(buffer, "UTF-8");
     }catch (Exception e) {
  }
  return result;
    }

 

ps: 继承 Activity

或者可以使用 context.getAssets().open(FileName);// 获取资源

 

评论关闭