Object Deserialization- to get back int array from serialized Object - java

int[] myIntArray;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new DeflaterOutputStream(byteArrayOutputStream));
objectOutputStream.writeObject(myIntArray);
Now,ObjectOutputStream takes The object and directly serializes it. DeflaterOutputStream compresses the serialized result, then the compressed result is stored in a ByteArrayOutputStream
Can Someone tell me How to Deserialize and get back my original int array back?
Plz Share the coding?

objectOutputStream.close();
byte[] serialized = byteArrayOutputStream.getBytes();
// and then read back using symmetric constructs as when writing, but using
// input streams instead of output streams:
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(serialized);
ObjectInputStream objectInputStream =
new ObjectInputStream(new InflaterInputStream(byteArrayInputStream));
int[] myDesererializedIntArray = (int[]) objectInputStream.readObject();

Related

ByteArrayOutputStream for shorts instead of bytes

I have used the ByteArrayOutputStream which is very useful but for my needs the limits are too great (ie I am dealing with numbers in the range +-32,768)
Here is the code where I would use it:
ByteArrayOutputStream leftStream = new ByteArrayOutputStream();
ByteArrayOutputStream rightStream = new ByteArrayOutputStream();
while (din.read(temp, 0, 4) != -1) {
if (decodedFormat.getChannels() == 2) {
leftStream.write(temp[1] * 256 + temp[0]);
rightStream.write(temp[3] * 256 + temp[2]);
}
}
byte[] left = leftStream.toByteArray();
byte[] right = rightStream.toByteArray();
However the ByteArrayInputStream does not allow for values over 127 or under 128. Is there an equivalent ShortArrayOutputStream that allows shorts? Or do I have to make one myself somehow?
Yes, Use the DataOutputStream:
ByteArrayOuputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeShort(val);
This works even on embedded java devices with low java version 1.3
To read in use:
ByteArrayInputStream and DataInputStream dis, and dis.readShort():
...
byte[] bytes = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bis);
short val = dis.readShort();
You can wrap the ByteArrayOutputStream into DataOutputStream:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
dataOutputStream.writeShort(someShortValue);
What do you want to do?
Write out short data to a byte array?
Then wrap your byte array output stream with a DataOutputStream which has methods to writeShort(), writeInt() etc. Warning. I think the endian of DataOutputStream is BIG endian so if you want to use little endian you either have to write it yourself or use the other option:
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataout = new DataOutputStream(byteOut)
dataout.writeShort(shortValue);
Write a short[]
the easiest is to create a ByteBuffer, then use the asShortBuffer() method to view it as a ShortBuffer. the ShortBuffer has a put(short) and put(short[]);
If you want to write out the short data in Little endian, ByteBuffer has a method asOrder(ByteOrder) which can change the endian of the data it is reading or writing.
//NOTE length should be 2* num shorts since we allocate in bytes
ByteBuffer buf = ByteBuffer.allocate(length);
ShortBuffer shortBuf = buf.asShortBuffer();
shortBuf.put(shortValue);
shortBuf.put(shortArray);
getting data out from buffers is annoying. There are optional array() methods but not all buffer impelmentations support them so you have to do the following:
//once all data written to buffer
shortBuf.flip();
short[] dataOut = new short[shortBuf.remaining()];
shortBuf.get(dataOut);
Combination of both to use a ShortBuffer on an unknown input size
If you don't know how many bytes you will write, and you don't have a reasonable, max length, then you may need to do a combination of both options. First, use option #1 to dynamically grow a byte buffer by writing shorts to it. Then convert the byte[] to a short[] with the ShortBuffer.
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataout = new DataOutputStream(byteOut)
dataout.writeShort(shortValue);
...
ShortBuffer buf =ByteBuffer.wrap(byteOut.toByteArray())
.asShortBuffer();
int length = buf.remaining();
short[] asShorts = new short[length];
buf.get(asShorts);
It's not pretty and uses 2x the memory since you make a copy of the array.
Create a ObjectOutputStream. This has a writeShort (http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeShort(int)) method.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeShort(123);
...

Convert android.graphics.Path object to byte[] and back

I'm trying to convert an android.graphics.Path object to byte[] so that I could store it in a blob storage in SQLite, also to convert it back.
So far I don't even know where to begin...
Thanks to anyone willing to help.
As Path extends Object, you can use something like this:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(path);
byte[] array = outputStream.toByteArray();
Serialize your object and upload that file .
ByteArrayOutputStream baos = new ByteArrayOutputStream()
ObjectOutput out = new ObjectOutputStream(baos);
out.writeObject(android.graphics.Path);
out.close()
byte[] buf = bos.toByteArray(); //byte array
to recover that object use deserialization
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf));
class_name recover =(clas_name) in.readObject();
in.close();
return object;

StreamCorruptedException when de-serializing through ObjectInputStream

I am trying to test a program and for that I need to access ReadExternal function but I am getting StreamCorrupted exception on ObjectInputStream.
I know I need to use the object written by WriteObject but dont know how to do it...
ObjectOutputStream out=new ObjectOutputStream(new ByteArrayOutputStream());
out.writeObject(ss3);
ss3.writeExternal(out);
try{
ByteInputStream bi=new ByteInputStream();
bi.setBuf(bb);
out.write(bb);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bb));
String s1=(String) in.readObject();
}
catch(Exception e){
e.printStackTrace();
}
Apparently, you are trying to write the same object twice to the output stream:
out.writeObject(ss3);
ss3.writeExternal(out); // <-- Remove this!
The second write makes wrong use of the writeExternal() method, which should never be called explicitly but will be called by the ObjectOutputStream.
And: out.write(bb); tries to write the content of bb to the ObjectOutputStream. That's probably not what you want.
Try it like this:
// Create a buffer for the data generated:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out=new ObjectOutputStream( bos );
out.writeObject(ss3);
// This makes sure the stream is written completely ('flushed'):
out.close();
// Retrieve the raw data written through the ObjectOutputStream:
byte[] data = bos.toByteArray();
// Wrap the raw data in an ObjectInputStream to read from:
ByteArrayInputStream bis = new ByteArrayInputStream( data );
ObjectInputStream in = new ObjectInputStream( bis );
// Read object(s) re-created from the raw data:
SomeClass obj = (SomeClass) in.readObject();
assert obj.equals( ss3 ); // optional ;-)
ss3.writeExternal(out);
You shouldn't be calling that method directly. You should be calling
out.writeObject(ss3);

ObjectOutputStream.toByteArray returns garbage

I need to get the byte array out of everything I send to the output stream. But instead I get 4 bytes of rubbish. Why?
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.write(new byte[]{1,2,3,4,5,6,7,8,9});
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original)); // why not [1,2,3,4,5,6,7,8,9]?
There are several flaws in your code. First of all you should use writeObject():
objectOutputStream.writeObject(new byte[]{1,2,3,4,5,6,7,8,9});
then you should use symmetric ObjectInputStream for reading:
final ObjectInputStream objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
)
);
byte[] original = (byte[]) objectInputStream.readObject();
However if you already have a byte[], there is no point in using Java serialization to convert it to byte array (which it already is!) Just write and read it directly:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9});
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
byteArrayOutputStream.toByteArray()
);
final byte[] original = new byte[9];
byteArrayInputStream.read(original);
System.out.println(Arrays.toString(original));
An ObjectOutputStream is not a OutputStream and if it did the same thing there wouldn't be much point in having it.
An ObjectOutputStream is used for writing Objects, it has a header (which you can see) and footer (which you can't see unless you close the stream)
You didn't write anything into the objectOutputStream, but some meta information, that comes with the ObjectOutputStream.
For the purpose of your small example you can use the ByteArrayOutputStream. Then You need to write the data into the stream using byteArrayOutputStream.flush().
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(new byte[]{1,2,3,4,5,6,7,8,9});
byteArrayOutputStream.flush();
byte[] original = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(original));
And don't forget to close the stream when you are done!
byteArrayOutputStream.close();
ObjectOutputStreams are used to serialize Objects.
If you want to serialize Objects you should use ObjectOutputStream#writeObject and ObjectInputStream#readObject.
Example : http://java.sun.com/developer/technicalArticles/Programming/serialization/

Serialize object with outputstream

Suppose I have an OutputStream (and not an ObjectOutputStream). Is is possible to send a serialized object using the write method? Thanks!
Here is what you do to serialize the object:
new ObjectOutputStream(outputStream).writeObject(obj);
If you want to control the byte[] output:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(buffer);
oos.writeObject(obj);
oos.close();
byte[] rawData = buffer.toByteArray();
You could use ObjectOutputStream to 'capture' the objects data in a byte Array and send this to the OutputStream.
String s = "test";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( s );
byte[] byteArray = baos.toByteArray();
for ( byte b : byteArray ) {
System.out.print( (char) b );
}
Another non generic option would be to serialize the object in a string representation e.g. CSV
This is trivial: you can simply wrap your original OutputStream in a new ObjectOutputStream, and then use the specialized methods of ObjectOutputStream:
OutputStream myOriginalOutputStream = ...;
ObjectOutputStream oos = new ObjectOutputStream(myOriginalOutputStream);
oos.writeObject(new MyObject());
oos.flush();
oos.close();
Internally, ObjectOutputStream will call the underlying OutputStream's write() method.
You must have to use ObjectOutputStream class and its methods to *serialize* objects. In fact ObjectOutputStream is a sub-class of java.io.OutputStream (It is an abstract super class of byte-oriented streams). Take a look at an article on Java Serialization API.
EDIT:
You can use XMLEncoder
(from the Doc : The XMLEncoder class is a complementary alternative to
the ObjectOutputStream and can used to generate a textual
representation of a JavaBean in the same way that the
ObjectOutputStream can be used to create binary representation of
Serializable objects)

Categories

Resources