将通过jbytearray传递的byte []写入文件

时间:2014-04-27 12:51:40

标签: java android c++ android-ndk java-native-interface

我需要将一个字节数组写入文件,然后使用jni传递给C ++中的函数。

这是我的Java代码

private void writeData(byte[] array) {
    Native nativeobject = new Native();

    long tsize = this.size;
    long incremental = 0;

    while(tsize != 0 && !this.stopped) {
        nativeobject.writeFile(whereToSave, array);

        publishProgress(incremental);
        incremental += TRANCE_SIZE;
        tsize -= TRANCE_SIZE;

    }
}

这是我的函数标题

JNIEXPORT jbyteArray JNICALL Java_it_mls_secureeraser_algorithms_Native_writeFile(JNIEnv *jni, jobject thiz,
        jstring jfileName, jbyteArray jarray) {

    const char *fileName = jni->GetStringUTFChars(jfileName, 0);

    int len = jni->GetArrayLength (jarray);
    unsigned char* buf = new unsigned char[len];
    jni->GetByteArrayRegion (jarray, 0, len, reinterpret_cast<jbyte*>(buf));

    FILE *output = fopen(fileName, "a+");
    fwrite(buf, sizeof(unsigned char*), sizeof(buf), output);
    fclose (output);
}

如何从jbytearray传递到我可以写入文件的内容? 谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

看看这里:A correct way to convert byte[] in java to unsigned char* in C++, and vice versa?。我之前遇到过类似的问题,这是解决方案。