How to convert contents of Java byte array to string C in JNI?


Update:

Error: jbyte* elements = (*env)->GetByteArrayElements(env, array, NULL);returns only 8 bytes. Provide any alternative to the jbytearray byte form method.


I am new to JNI, so I am not familiar with JNI, as well as English.

Now I try a simple JNI program to read a file in Java and write it to a file using C.

Script for reading files:

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 file write 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 tried many solutions (below the link), but could not write it to a file. Please provide the right solution and the best JNI training site.

Already tested solution: (But not success)

Correct way to convert byte [] in java to unsigned char * in C ++ and vice versa?

Convert jbyteArray to an array of characters and then print to the 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);

GetByteArrayElements jbyte 8, GetArrayLength 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;
}

:

Done
Number of jByte element   : 50335
Number of Byte elements   : 8
Number of buffer elements : 8
+4
1

@Olaf, . . , , , .

, Java fputs(), , C, Java, , , jbyteArray , , , . , , . , , , . " ".

. , C -, Java , . , jbytearray , JNI . , , .

:

// determine the needed length and allocate a buffer for it
jsize num_bytes = GetArrayLength(env, array);
char *buffer = malloc(num_bytes + 1);

if (!buffer) {
    // handle allocation failure ...
}

// obtain the array elements
jbyte* elements = GetByteArrayElements(env, array, NULL);

if (!elements) {
    // handle JNI error ...
}

// copy the array elements into the buffer, and append a terminator
memcpy(buffer, elements, num_bytes);
buffer[num_bytes] = 0;

// Do not forget to release the element array provided by JNI:
ReleaseByteArrayElements(env, array, elements, JNI_ABORT);

, buffer , , , fputs():

int result = fputs(buffer, file);

, , , , :

free(buffer);

, , , strlen() , . , - , .

Update

- C. , , , C fputs() , , . @Michael, , , , .

, C . . , , fprintf() :

fprintf("%*s", (int) num_bytes, (char *) elements);

, , . :

#include <stdio.h>
#include <jni.h>
#include "FileIO.h"

JNIEXPORT void JNICALL Java_FileIO_writeToFile(JNIEnv *env, jobject job,
        jbyteArray array) {
    FILE *fp = fopen( "file.txt" , "w" );

    if (!fp) {
        // handle failure to open the file ...
    }

    // determine the needed length and allocate a buffer for it
    jsize num_bytes = GetArrayLength(env, array);

    // obtain the array elements
    jbyte* elements = GetByteArrayElements(env, array, NULL);

    if (!elements) {
        // handle JNI error ...
    }

    // output the data
    if (fwrite(elements, 1, num_bytes, fp) != num_bytes) {
        // handle I/O error ...
    }

    // Do not forget to release the element array provided by JNI:
    ReleaseByteArrayElements(env, array, elements, JNI_ABORT);

    fclose(fp);
}
+3

Source: https://habr.com/ru/post/1650178/


All Articles