更新:
错误:`jbyte* elements = (*env)->GetByteArrayElements(env, array, NULL);` 只返回 8 个字节。请提供其它检索 jbytearray 的方法。
我是JNI的新手,对JNI和英语都不太熟悉。
现在我正在尝试用Java读取文件并使用C将其写入文件的简单JNI程序。
Java文件读取代码:
public class FileIO {
static {
System.loadLibrary("io");
}
private native void writeToFile(byte[] msg);
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=null;
File file = new File("version1-1.png");
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
System.out.println("Done");
} catch(Exception e){
e.printStackTrace();
}
new FileIO().writeToFile(bFile);
}
}
文件写入的C代码:
#include <jni.h>
#include <stdio.h>
#include <string.h>
#include "FileIO.h"
JNIEXPORT void JNICALL Java_FileIO_writeToFile (JNIEnv *env, jobject job, jbyteArray array ){
char * buf ;
// here what i do ??? :(
FILE *file = fopen("test123.png", "w");
int results = fputs(buf, file);
if (results == EOF) {
//Failed to write do error code here.
}
fclose(file);
}
我已经尝试了许多解决方案(下面的链接),但是在将其写入文件时没有成功。请提供正确的解决方案和最佳JNI教程网站。
已经尝试的解决方案:(但没有成功) 在Java中正确地将byte[]转换为C++中的unsigned char*,反之亦然? 将jbyteArray转换为字符数组,然后打印到控制台 如何在jni中将jbyteArray转换为本地char*?
int len = (*env)->GetArrayLength (env , array );
printf(" Length of the bytearray %d\n", len );
unsigned char * string ;
string = (char *)malloc((len + 1) * sizeof(char)) ;
jbyte* b = (*env)->GetByteArrayElements(env, array, &isCopy);
在调用
GetByteArrayElements
函数之后,jbyte的长度应该是8,但是GetArrayLength
返回的bytearray的长度为50,335。我尝试过的方法:
JNIEXPORT void JNICALL Java_HelloJNI_sayHello (JNIEnv *env, jobject job, jbyteArray array ){
jsize num_bytes = (*env)->GetArrayLength(env, array);
char *buffer = malloc(num_bytes + 1);
printf("Number of jByte element : %d\n", (int) num_bytes);
if (!buffer)
printf("Buff Fail\n");
jbyte* elements = (*env)->GetByteArrayElements(env, array, NULL);
if (!elements)
printf("Element Fail\n");
printf ("Number of Byte elements : %d\n", (int) strlen (elements));
memcpy(buffer, elements, num_bytes);
buffer[num_bytes] = 0;
printf("Number of buffer elements : %d\n", (int) strlen(elements));
(*env)->ReleaseByteArrayElements(env, array, elements, JNI_ABORT);
FILE *fp;
fp = fopen( "file.txt" , "w" );
fwrite(buffer , 1 , sizeof(buffer) , fp );
fclose(fp);
return;
}
AND输出:
Done
Number of jByte element : 50335
Number of Byte elements : 8
Number of buffer elements : 8