I am using the latest version of Android Studio (2.2.3) and I have loaded up the HelloGL2 sample project.
I now want to add a file (any type of file) to my app, and then be able to open it and read it in the c++ code using something like c's fopen etc (any direct file access api is fine)
How do I do this?
There are two options, it will depend on your target. If your file is a basic text configuration file, you can use both cases, but if your file is a 3D object such as (.obj, .max, .dae) you should use AssetManager class.
First option: (store your files in res raw (You can use fopen())).
In 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();
}
}
Then, call to your function:
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"); }
Second option (use assetManager, usually for opengl resources).
The parameter, in this case, is not the path of the directory is the asset manager.
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); }
Note: Do not forget to add the permissions in your AndroidManifest.xml.
Note II: Do not forget to add:
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
I hope this answer helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With