Reputation: 1567
my code is as follows..
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;
}
code for converting object to byte array is:-
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;
}
when i compare the length of the both the byte arrays its different.some extra byte are added but at which point of conversion..?(while assigning the byte array to object or when) Size of input Stream comes same as first byte array.
I want to convert the Inputstream of http request into a resObject which can be then given to outputstream.Using ObjectInputStream.readObject() gives StreamCorruptedException.
Upvotes: 3
Views: 1369
Reputation: 360
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);
Upvotes: 0
Reputation: 691785
You're serializing a byte array using Java object serialization. This has an overhead over the raw byte array, since the serialized stream contains a serialization header, the name of the class of the object being serialized, and probably some additional bytes to be able to know where the object starts and ends in the stream.
Remember that, when deserializing, the receiver knows nothing about the contents of the ObjectInputStream. So it must be able to know that what has been serialized is a single byte array (and not a String, an Integer or any other serializable object). So this information has to be stored somehow in the stream, and thus needs some additional bytes.
Upvotes: 8