How do I read a binary file in C++ if I generate it in Java? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I read a binary file in C++ if I generate it in Java? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m working on an encryption algorithm and I need to generate some information in Java (a binary file) to read in C++.

I’m not sure if the problem is how I create the binary file or how I read it, though I can perfectly read the information in Java.

So I made a simple test. In Java I save the number 9 to a binary file, and then I try to read it in C++, but it does not read a number.

Can someone please tell me how I can do this?

The Java code:

int x = 9;

        try{
            ObjectOutputStream salida=new ObjectOutputStream(new 
            FileOutputStream("test.bin"));
            salida.writeInt(x);
            salida.close();
            System.out.println("saved");
        } catch(Exception e){
            System.out.println(e);
        }

The C++ code:

streampos size;
  char * memblock;

  ifstream file ("test.bin", ios::in|ios::binary|ios::ate);
  if (file.is_open())
  {
    size = file.tellg();
    cout<< size << endl;
    memblock = new char [size];
    file.seekg (0, ios::beg);
    file.read (memblock, size);
    file.close();

    int i;
    for (i = 0; i < sizeof(memblock); i++)
    {
        cout << memblock[i] <<endl;
    }
 delete[] memblock;
  }
  else cout << "Unable to open file";

This is the output:

�
�


w

Answer

Your problem is that you are using ObjectOutputStream to write the data. This encodes the object graph in a Java-specific form intended to be read with ObjectInputStream. To make the data stream compatible with C++ you would need to do one of two things:

  1. Implement in C++ code that understands the output format produced by ObjectOutputStream — i.e. re-implement in C++ what Java does in ObjectInputStream. This is NOT recommended.
  2. Write your data out from Java using a standard FileOutputStream, in a serialized format that you define, that then can be read by your C++ code. How you specify and implement this is up to you but can be very simple, depending on the complexity of your data.
We are here to answer your question about How do I read a binary file in C++ if I generate it in Java? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji