[英]How to write jbyteArray( or byte array) to txt file c++?
I have an image in a form that jbytearray in c++.我在 c++ 中有一个 jbytearray 格式的图像。 I need to write it to txt file.
我需要将其写入 txt 文件。 I did many solutions on stackoverflow but none of them worked for me.
我在 stackoverflow 上做了很多解决方案,但没有一个对我有用。
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++.当我将jbyteArray转换为char *时,它写入成功,但我需要将它写为jbyteArray,因为我需要比较jbyteArray在java和c++中的内容。 I write jbyteArrays which comes from c++ to txt file and also I need to jbytesArray in c++ part.
我将来自 c++ 的 jbyteArrays 写入 txt 文件,并且我还需要在 c++ 部分中写入 jbytesArray。 Therefore I need to write jbyteArray as jbyteArray not as char *
因此我需要将 jbyteArray 写为 jbyteArray 而不是 char *
Here is what i tried;这是我尝试过的;
Trial 1试验 1
std::ofstream("myfile.bin", std::ios::binary).write(data, 100);
Problem with Trial 1试验 1 的问题
Argument of type "jbyteArray" is incompatible with parameter of type "const char *" “jbyteArray”类型的参数与“const char *”类型的参数不兼容
Thank You very much.非常感谢您。
You need to get a jbyte*
from the jbytearray
, which is a Java object:您需要从
jbytearray
获取一个jbyte*
,即 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 类和本机库后:
$ java -Djava.library.path=$(pwd) -cp . Main foobar
$ cat myfile.bin
foobar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.