Android读取assets目录下文件数据内容
Android的体系架构设计中,assets目录下的数据内容(图片、文件等等)将不会被Android系统压缩、二次处理等,assets目录下的文件将保持原汁原味打包进Android的apk文件中,因此,利用Android assets这一点特性,根据项目开发的需要,在某种情况下,可以在assets目录下存放一些不希望被Android系统二次处理的原始文件,就像在PC开发时候直接针对硬盘上存放的文件内容进行读写一样读出原始数据。比如Android项目中有以下assets文件目录结构,如图:
![](https://img-blog.csdn.net/20150906182314100?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
现给出代码实例:
- public String readAsset() {
- AssetManager am = this.getAssets();
- String[] path = null;
- try {
-
- path = am.list("files");
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- String data = "";
-
-
- for (int i = 0; i < path.length; i++) {
- InputStream is = null;
- try {
-
- is = am.open("files/" + path[i]);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
-
- data = data + readDataFromInputStream(is) + "\n";
-
- try {
- is.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return data;
- }
-
- public String readDataFromInputStream(InputStream is) {
- BufferedInputStream bis = new BufferedInputStream(is);
-
- String str = "", s = "";
-
- int c = 0;
- byte[] buf = new byte[64];
- while (true) {
- try {
- c = bis.read(buf);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- if (c == -1)
- break;
- else {
- try {
- s = new String(buf, 0, c, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- str += s;
- }
- }
-
- try {
- bis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return str;
- }
其中,this指针为当前的Context或者Activity。