Update:
Error: jbyte* elements = (*env)->GetByteArrayElements(env, array, NULL);
returns only 8 bytes. Provide any alternative to way to retrieve byte form jbytearray.
I'm new in JNI so I'm not familiar in JNI and also English.
Now I try the simple JNI program on File reading in Java and write it into file using C.
File reading java code:
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);
}
}
File write C code:
#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);
}
I have tried many solutions (below link) but no luck in writing it to the file. Please provide the correct solution and best JNI tutorial site.
Already tried solution: (But not success)
A correct way to convert byte[] in java to unsigned char* in C++, and vice versa?
Converting jbyteArray to a character array, and then printing to console
How to convert jbyteArray to native char* in jni?
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);
After GetByteArrayElements
jbyte length should be 8 but the GetArrayLength
returns bytearray length is 50,335.
What i try :
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 the Output:
Done
Number of jByte element : 50335
Number of Byte elements : 8
Number of buffer elements : 8