Last active
          August 29, 2015 14:16 
        
      - 
      
- 
        Save yorung/4fe664d389185b75ba23 to your computer and use it in GitHub Desktop. 
    [Android] load file from assets folder
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public class Helper { | |
| private static Context context; | |
| public static void setContext(Context c) { context = c; } | |
| public static byte[] loadIntoBytes(String fileName) { | |
| AssetManager assetManager = context.getAssets(); | |
| try { | |
| InputStream is = assetManager.open(fileName); | |
| byte buf[] = new byte[is.available()]; | |
| is.read(buf); | |
| return buf; | |
| } catch (IOException e) { | |
| } | |
| return null; | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const char* boundJavaClass = "common/pinotnoir/Helper"; | |
| void *LoadFile(const char *fileName, int* size) | |
| { | |
| jclass myview = jniEnv->FindClass(boundJavaClass); | |
| jmethodID method = jniEnv->GetStaticMethodID(myview, "loadIntoBytes", "(Ljava/lang/String;)[B"); | |
| if (method == 0) { | |
| return nullptr; | |
| } | |
| jobject arrayAsJObject = jniEnv->CallStaticObjectMethod(myview, method, jniEnv->NewStringUTF(fileName)); | |
| jbyteArray array = (jbyteArray)arrayAsJObject; | |
| jbyte* byteArray = jniEnv->GetByteArrayElements(array, NULL); | |
| jsize arrayLen = jniEnv->GetArrayLength(array); | |
| void* ptr = calloc(arrayLen + 1, 1); | |
| memcpy(ptr, byteArray, arrayLen); | |
| if (size) { | |
| *size = arrayLen; | |
| } | |
| jniEnv->ReleaseByteArrayElements(array, byteArray, 0); | |
| return ptr; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment