【问题标题】:Write byte[] passed through jbytearray to a file将通过 jbytearray 传递的 byte[] 写入文件
【发布时间】:2014-04-27 12:51:39
【问题描述】:

我需要将我使用 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 传递到可以写入文件的内容? 感谢帮助

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 效果不太好..我的数组大小是1KB,但是当我写它的一部分时,它只写了0,02KB
    • 您是否检查过转换是否正常?我查看了我的代码,我使用的代码与上面的帖子完全相同。可能你写的有误?
    • 转换效果很好.. fwrite 出了点问题
    • 试试这样的:fwrite(buf, sizeof(unsigned char), sizeof(buf)/sizeof(unsigned char), output);
    • 还是不行,每次写入4字节(0000)(而不是1048576)_静态写入解决:fwrite(buf, 1, 1048576, output);动态写作呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多