[英]How do I add a file to an Android project and then load it using the NDK
我使用的是最新版本的Android Studio(2.2.3),我已經加載了HelloGL2示例項目。
我現在想要在我的應用程序中添加一個文件(任何類型的文件),然后能夠打開它並使用c的fopen等在c ++代碼中讀取它(任何直接文件訪問api都可以)
我該怎么做呢?
有兩種選擇,它取決於您的目標。 如果您的文件是基本文本配置文件,則可以使用這兩種情況,但如果您的文件是(.obj,.max,.dae)等3D對象,則應使用AssetManager類。
第一個選項:(以res raw存儲您的文件(您可以使用fopen()))。
在Java中:
public void writeFileToPrivateStorage(int fromFile, String toFile)
{
InputStream is = mContext.getResources().openRawResource(fromFile);
int bytes_read;
byte[] buffer = new byte[4096];
try
{
FileOutputStream fos = mContext.openFileOutput(toFile, Context.MODE_PRIVATE);
while ((bytes_read = is.read(buffer)) != -1)
fos.write(buffer, 0, bytes_read); // write
fos.close();
is.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
然后,調用您的函數:
writeFileToPrivateStorage(R.raw.your_file,"your_output_file.txt");
path=mContext.getApplicationContext().getFilesDir().toString();
public static native void setconfiguration(String yourpath);
JNIEXPORT void JNICALL Java_com_android_gl2jni_GL2JNILib_setconfiguration(JNIEnv * env, jobject obj, jstring path) { //convert your string into std::string. const char *nativeString = env->GetStringUTFChars(config_path, 0); //make here your fopen. fopen(nativeString,"r"); }
第二個選項(使用assetManager,通常用於opengl資源)。
在這種情況下,參數不是目錄的路徑,即資產管理器。
public static native void yourfunction(AssetManager assetManager);
loadYourFile(m_context.getAssets());
JNIEXPORT void Java_com_android_gl2jni_GL2JNILib_(JNIEnv * env, jobject obj,jobject java_asset_manager) { AAssetManager* mgr = AAssetManager_fromJava(env,java_asset_manager); 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); }
注意:不要忘記在AndroidManifest.xml中添加權限。
注意二:不要忘記添加:
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
我希望這個答案可以幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.