美文网首页
jni 提取 assets 目录下的文件

jni 提取 assets 目录下的文件

作者: that_is_this | 来源:发表于2018-03-26 15:08 被阅读319次

    传入参数 :
    ctx = context
    dir = 文件路径
    szDexPath = ......jiami.dat
    fileName = jiami.dat

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <android/asset_manager.h>
    #include <android/asset_manager_jni.h>
    
    int extract_file(JNIEnv* env, jobject ctx, const char* dir,const char* szDexPath,const char* fileName)
    {
    
        if (access(dir, F_OK) !=0) {        // 判断 这两个路径、文件是否存在
            mkdir(dir, 505);
            chmod(dir, 505);
        }
    
        if (access(szDexPath,F_OK)==0) {
          LOGD("[+]File %s have existed",szDexPath);
            return 0;
        }
        //jiami.dat不存在,开始提取
        else {
            AAssetManager* mgr;
            jclass ApplicationClass = env->GetObjectClass(ctx);
            jmethodID getAssets = env->GetMethodID(ApplicationClass, "getAssets", "()Landroid/content/res/AssetManager;");
            jobject Assets_obj = env->CallObjectMethod(ctx, getAssets);
            mgr = AAssetManager_fromJava(env, Assets_obj);      // 获取 AssetManager 对象
            if (mgr == NULL) {
                LOGE("[-]getAAssetManager failed");
                return 0;
            }
            AAsset* asset = AAssetManager_open(mgr, fileName, AASSET_MODE_STREAMING);   // 获取 asset 对象,对应的文件名    UNKNOWN 0, RANDOM 1, STREAMING 2, BUFFER 3
            FILE* file = fopen(szDexPath, "wb");        // wb 只写打开或新建一个二进制文件;只允许写数据
            int bufferSize = AAsset_getLength(asset);       // 长度
            LOGD("[+]Asset FileName:%s,extract path:%s,size:%d\n",fileName,szDexPath, bufferSize);      // Asset FileName:jiami.dat, extract path:/data/data/com.wangwz.ndk_test/files/.jiagu/jiami.dat, size:2639568
            void* buffer =malloc(4096);
            while (true) {
                int numBytesRead = AAsset_read(asset, buffer, 4096);
                if (numBytesRead <= 0)
                    break;
                fwrite(buffer, numBytesRead, 1, file);      // 写入到 file 内
            }
            free(buffer);
            fclose(file);
            AAsset_close(asset);
            chmod(szDexPath, 493);
        }
    }
    

    相关文章

      网友评论

          本文标题:jni 提取 assets 目录下的文件

          本文链接:https://www.haomeiwen.com/subject/snjrcftx.html