Tobseb
Tobseb

Reputation: 15

How to (de)serialize correctly to a byte-array using a ObjectOutputStream & ObjectInputStream?

I am aware that an ObjectOutputStream/ObjectInputStream uses headers and this is not really a proper use-case. But anyway I need to wrap some data into it using the interfaces DataInput and DataOutput.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        byte[] array = serialize("test");
        String deserialized = deserialize(array);

        System.out.println(deserialized);
    }

    private static byte[] serialize(String test) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

            objectOutputStream.writeUTF(test);

            byteArrayOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();
    }

    private static String deserialize(byte[] array) {
        String temp = null;

        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(array));

            temp = objectInputStream.readUTF();

            objectInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return temp;
    }
}

I don't really get how to get that working. Am I right, that the problem are those headers currently?

Upvotes: 1

Views: 454

Answers (1)

talex
talex

Reputation: 20455

You should call objectOutputStream.flush(); before closing byteArrayOutputStream.

ObjectOutputStream have its internal buffer so you got only beginning of string in your byte array.

Upvotes: 2

Related Questions