简体   繁体   中英

How to write jbyteArray( or byte array) to txt file c++?

I have an image in a form that jbytearray in c++. I need to write it to txt file. I did many solutions on stackoverflow but none of them worked for me.

when I cast jbyteArray into char *, it is successfully write it, but i need to write it as a jbyteArray, because I need to compare jbyteArray's content in java and c++. I write jbyteArrays which comes from c++ to txt file and also I need to jbytesArray in c++ part. Therefore I need to write jbyteArray as jbyteArray not as char *

Here is what i tried;

Trial 1

std::ofstream("myfile.bin", std::ios::binary).write(data, 100);

Problem with Trial 1

Argument of type "jbyteArray" is incompatible with parameter of type "const char *"

Thank You very much.

You need to get a jbyte* from the jbytearray , which is a Java object:

public class Sample {
    public static final native void write(byte[] byteArray);
}
#include <jni.h>
#include <fstream>

extern "C" JNIEXPORT void JNICALL Java_Sample_write(JNIEnv *env,
                                                    jclass,
                                                    jbyteArray jba) {
    jbyte *arr = env->GetByteArrayElements(jba, nullptr);
    if (!arr) {
        return;
    }
    jint len = env->GetArrayLength(jba);

    std::ofstream("myfile.bin", std::ios::binary)
            .write(reinterpret_cast<char *>(arr), len);

    env->ReleaseByteArrayElements(jba, arr, JNI_ABORT);
}

You can test with:

project(sample_jni)
cmake_minimum_required(VERSION 2.8.8)

include(FindJNI)
if (JNI_FOUND)
    message(STATUS "JNI_INCLUDE_DIRS=${JNI_INCLUDE_DIRS}")
    message(STATUS "JAVA_JVM_LIBRARY=${JAVA_JVM_LIBRARY}")
else()
    message(FATAL_ERROR "Found JNI: failed")
endif()

if(MSVC)
    add_definitions(-D_CRT_SECURE_NO_WARNINGS=1 -Dstrdup=_strdup -Dputenv=_putenv)
endif()

if(NOT(MSVC))
    add_compile_options(-Wall -Wno-padded -Wno-unknown-pragmas -Wno-switch -Werror)
endif()

set(SOURCE_FILES
    jni.cpp)
add_library(sample_jni SHARED ${SOURCE_FILES})

set_target_properties(sample_jni PROPERTIES
    C_VISIBILITY_PRESET hidden)

target_include_directories(sample_jni PRIVATE ${JNI_INCLUDE_DIRS})
import java.nio.charset.Charset;

public class Main {
    public static void main(String[] args) {
        System.loadLibrary("sample_jni");
        byte[] bytes = args[0].getBytes(Charset.forName("UTF-8"));
        Sample.write(bytes);
    }
}

After compiling both the Java classes and the native lib:

$ java -Djava.library.path=$(pwd) -cp . Main foobar
$ cat myfile.bin 
foobar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM