Android read text file from asset folder using C (ndk)

Here is the code I used to read file from android assets folder using asset_manager ndk lib

    AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
    AAsset* asset = AAssetManager_open(mgr, (const char *) js, AASSET_MODE_UNKNOWN);
    if (NULL == asset) {
        __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, "_ASSET_NOT_FOUND_");
        return JNI_FALSE;
    }
    long size = AAsset_getLength(asset);
    char* buffer = (char*) malloc (sizeof(char)*size);
    AAsset_read (asset,buffer,size);
    __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, buffer);
    AAsset_close(asset);

Added following line to my Android.mk

# for native asset manager
LOCAL_LDLIBS    += -landroid

And don’t forget the include in source file

#include <android/asset_manager.h>

Leave a Comment