将字节数组转换为对象会增加大小吗?

时间:2014-08-25 07:06:07

标签: java arrays bytearray

我的代码如下..

private Object populateObj(InputStream inputStream) {
        int i=0;
        Object resObject = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int next = inputStream.read();
            while (next > -1) {
                i++;
                bos.write(next);
                next = inputStream.read();
            }
            bos.flush();
            byte[] result = bos.toByteArray();
            System.out.println("Size of byte array 1: "+result.length);
            System.out.println("Result is []");
            for(int j=0;j<result.length;j++){
                System.out.println(result[j]);
            }
            resObject = result;
            byte[]  result2=toByteArray(resObject);
            System.out.println("Size of byte array 2 : "+result2.length);
            System.out.println("Result2 is []");
            for(int j=0;j<result.length;j++){
                System.out.println(result2[j]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("size of inputStream in bytes : "+i);
        return resObject;
    }

将对象转换为字节数组的代码是: -

public static byte[] toByteArray(Object obj) throws IOException {
        byte[] bytes = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
        } finally {
            if (oos != null) {
                oos.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
        return bytes;
    }

当我比较两个字节数组的长度时,它的不同。添加了一些额外的字节,但在转换的哪一点......?(同时将字节数组分配给对象或何时) 输入Stream的大小与第一个字节数组相同。

我想将http请求的Inputstream转换为resObject,然后将其赋予outputstream.Using ObjectInputStream.readObject()给出StreamCorruptedException。

2 个答案:

答案 0 :(得分:8)

您正在使用Java对象序列化序列化字节数组。这比原始字节数组有开销,因为序列化流包含序列化头,被序列化对象的类的名称,以及可能知道对象在流中开始和结束的位置的一些额外字节。

请记住,在反序列化时,接收者对ObjectInputStream的内容一无所知。因此,必须能够知道已序列化的是单字节数组(而不是字符串,整数或任何其他可序列化对象)。所以这些信息必须以某种方式存储在流中,因此需要一些额外的字节。

答案 1 :(得分:0)

    byte[] array = new byte[] { 1, 2, 3, 4 };
    System.out.println(array.length);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(array);
    oos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Object obj = ois.readObject();
    ois.close();

    System.out.println(((byte[]) obj).length);