mat*_*att 5 c++ file-io android android-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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,调用您的函数:
writeFileToPrivateStorage(R.raw.your_file,"your_output_file.txt");
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我希望这个答案可以帮到你.