-1

I need to write into a file a byte array that i pass to a function in C++ using jni.

That's my Java code

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;

    }
}

And that's my function header

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);
}

how can I pass from jbytearray to something that I can write to my file? Thanks for help

Angelo Cassano
  • 180
  • 1
  • 4
  • 16

1 Answers1

2

Have a look here: A correct way to convert byte[] in java to unsigned char* in C++, and vice versa?. I faced similar problem before and it was the solution.

Community
  • 1
  • 1
haxtron
  • 46
  • 8
  • It doesn't work pretty well.. My array size is 1KB, but when I write a tranche of it, it only writes 0,02KB – Angelo Cassano Apr 27 '14 at 13:48
  • Have you checked that conversion is ok? I looked my code, and I used exactly the same code as the post above. Maybe you have some errors on writing? – haxtron Apr 27 '14 at 13:59
  • Conversion works pretty well.. something is wrong with fwrite – Angelo Cassano Apr 27 '14 at 14:40
  • Try something like this: fwrite(buf, sizeof(unsigned char), sizeof(buf)/sizeof(unsigned char), output); – haxtron Apr 27 '14 at 14:52
  • Still not working, it wrote 4bytes (0000) per time (instead of 1048576) _ Solved by statically writing: fwrite(buf, 1, 1048576, output); What about dinamically writing? – Angelo Cassano Apr 27 '14 at 14:56
  • Try with: fwrite(buf, sizeof(unsigned char), len/sizeof(unsigned char), output);. – haxtron Apr 27 '14 at 15:00
  • "len/sizeof(unsigned char)" it is not neccesary, with "len" should work too. Copy-pasting errors :). – haxtron Apr 27 '14 at 15:24