JNI help with reading C binaries and writing in Java

3

I have to make a program that reads binary files of any kind from C and through JNI pass the read bytes to java. That part is already, what I need is to write a new file in Java and pass all the data that collects C. I put the code that I have, thanks.

//C code
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
JNIEXPORT jobjectArray JNICALL Java_ReadFileJNI_readfile(JNIEnv *env, jobject jobj)
{

//the variables are initialized
jstring str;
jsize len = 1;
jobjectArray objectarray = 0;

//Create variable rate "File" is prompter and call fopen "rb" -> leer archivo/tipo binario
FILE * flujo = fopen("Datos.txt","rb");

// Mueve el flujo al final del archivo, SEEK_END -> final del archivo  
fseek(flujo, 0 , SEEK_END);

/* Da la cantidad total de elementos ya que el ftell pregunta donde 
   se encuentra el flujo y eso se almacena en la variable 
*/
int num_elementos = ftell(flujo);

//Mueve el flujo al inicio del archivo
rewind(flujo);

/* Crear un arreglo de caracteres dinámico, calloc-> de que tamaño en bytes    va a ser cada elemento del arreglo 
   se le manda cuanta cantidad de elementos quiere reservar
*/
unsigned char * cadena = (unsigned char *) calloc(sizeof(unsigned char), num_elementos);

/* fread recibe un arreglo donde meterá todo el contenido del flujo y que    tamaño es elemento que se quiere leer
   y cuantos se quieren leer y como se quieren leer todos se pone el # de   elementos  y se le manda de donde 
   extraerá la información
*/
int num_elemetos_leidos = fread(cadena,sizeof(unsigned char),  num_elementos,flujo);

//Se realiza la asignación del arreglo para enviarlo    
objectarray = (*env)->NewObjectArray(env,len,(*env)- >FindClass(env,"java/lang/String"),0);
str = (*env)->NewStringUTF(env,cadena);
(*env)->SetObjectArrayElement(env,objectarray,0,str);

//se libera memoria dinámica de la cadena y se cierra el flujo 
free(cadena);
fclose(flujo);
return objectarray;
}

This is the Java code:

//código java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ReadFileJNI
{
    native String[] readfile();

    static{ System.loadLibrary("ReadFileJNI"); }

    static public void main(String args[])
    {

      ReadFileJNI obj = new ReadFileJNI();
      String[] buffer = obj.readfile();

      System.out.println(" El arreglo desde C es: \n ");
      for(String name: buffer)
        System.out.println(name);

        try {

            //String content = name;
            File file = new File("ruta donde se creara el archivo");

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            for(String name: buffer)
            System.out.println(name);
            bw.write(String name);
            bw.close();

            System.out.println("Done");

        } 
        catch (IOException e) { e.printStackTrace(); }
    }
}
    
asked by Edu Arias 26.10.2016 в 00:28
source

1 answer

0

Try this

  for(String name: buffer){
        System.out.println(name);
        bw.write(name);
}            
bw.close();

Instead of this:

for(String name: buffer) //Solo iteras System.
    System.out.println(name);
    bw.write(String name); //es error de compilación el String.
    bw.close();

Remember that the for only alters the next element and that the data type should not be placed in the objects.

    
answered by 26.10.2016 / 01:12
source