android JNI开发C++代码对assets文件的访问

来源:互联网 发布:国泰安数据库好用吗 编辑:程序博客网 时间:2024/06/04 23:31

由于在apk的安装过程中assets中的文件并没有从apk包中解压出来,所以在JNI的C++代码中不能按照原始的路径直接进行访问,一种常用的方法为将assets中的文件复制到sdcard的目录下,然后传递绝对路径给JNI中的C++代码中进行访问。

/** * copy the files and folders of assets to sdCard to ensure that we can read files in JNI part  * @author Qinghao Hu * @date   2015/9/22 * @version 1.0 * @email qinghao.hu@nlpr.ia.ac.cn */package com.hqh.utils;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.content.res.AssetManager;import android.util.Log;public class AssetCopyer {private static String TAG="AssetCopyer";/** * copy all the files and folders to the destination  * @param context  application context * @param destination the destination path */public  static void copyAllAssets(Context context,String destination){copyAssetsToDst(context,"",destination);}/** *  * @param context :application context * @param srcPath :the path of source file * @param dstPath :the path of destination */private  static void copyAssetsToDst(Context context,String srcPath,String dstPath) {                    try {String fileNames[] =context.getAssets().list(srcPath);if (fileNames.length > 0){ File file = new File(dstPath);file.mkdirs();for (String fileName : fileNames) {if(srcPath!=""){copyAssetsToDst(context,srcPath + "/" + fileName,dstPath+"/"+fileName);}else{copyAssetsToDst(context, fileName,dstPath+"/"+fileName);}}}else {InputStream is = context.getAssets().open(srcPath);FileOutputStream fos = new FileOutputStream(new File(dstPath));byte[] buffer = new byte[1024];int byteCount=0;               while((byteCount=is.read(buffer))!=-1) { fos.write(buffer, 0, byteCount);}fos.flush();//刷新缓冲区is.close();fos.close();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}                           }}
使用过程很简单,调用静态方法即可。由于Android系统在sdcard上为每一个应用分配了存储路径:/sdcard/Android/data/$(应用的包路径), 该路径可以通过 context.getExternalFilesDir 得到,一般应用卸载的时候,该目录也会随之被删除。

所以可以把assets中的文件中的文件复制到这个文件夹下,调用方式为:

AssetCopyer.copyAllAssets(this.getApplicationContext(),this.getExternalFilesDir(null).getAbsolutePath());


to be continued ........

0 0
原创粉丝点击