Regarding serializing the array list object - java

I have an array list that I want to serialize please advise how to I will be able to do that..
ArrayList list=new ArrayList();
list.add("Ram");
list.add("Sachin");
list.add("Dinesh");
list.add(1,"Ravi");
list.add("Dinesh");
list.add("Anupam");
System.out.println("There are "+list.size()+" elements in the list.");
System.out.println("Content of list are : ");
Iterator itr=list.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
}
I want to use the serialization mechanism so that I can save it in file

It is very simple. Both ArrayList and String (that you store in the list) implement Serializable interface, so you can use the standard java mechanism for serialization:
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myfile"));
oos.writeObject(list);
............
oos.fluch();
oos.close();
In this example I wrapped FileOutputStream with ObjectOutputStream but obviously you can use any other payload stream.

You have to create your own methods for serializing and deserializing objects. The below are useful methods for doing just that.
public static Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bytesIn);
Object obj = ois.readObject();
ois.close();
return obj;
}
public static byte[] serializeObject(Object obj) throws IOException
{
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
oos.writeObject(obj);
oos.flush();
byte[] bytes = bytesOut.toByteArray();
bytesOut.close();
oos.close();
return bytes;
}

Related

How to serialize and deserialise list of objects in Java? [duplicate]

This question already has answers here:
Converting any object to a byte array in java
(5 answers)
Closed 7 years ago.
I have a List<Animal> that i want to send as a SOAP response to the client but the send method requires byte[] and deserialize in the client.
Can anyone tell me how to convert my List<Animal> to byte[] and convert the byte[] back to the List<Animal>.
I know there is lots of questions like this in this site, but I am confuse with the answers. I tried a lot of them but none of the worked for me.
It depends on Animal. If it is Serializable you can use Java Serialization mechanizm https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html.
public static byte[] objectToByteArray(Object obj) throws Exception {
byte[] bytes = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
bytes = baos.toByteArray();
oos.close();
return bytes;
}
public static Object byteArrayToObject(byte[] buffer) throws Exception {
Object ob = null;
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
buffer));
ob = ois.readObject();
ois.close();
return ob;
}

Convert ArrayList to byte array

I have a code where I am converting array list to byte array and then saving that byte array as a BLOB in MySQL database. Below is code:-
Object temp = attributes.get(columnName);
if (temp instanceof List && temp != null) {
List extraAttributes = (ArrayList) temp;
resultStmt.setBytes(currentIndex, createByteArray(extraAttributes));
The method createByteArray is defined as below:
private byte [] createByteArray( Object obj)
{
byte [] bArray = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objOstream = new ObjectOutputStream(baos);
objOstream.writeObject(obj);
bArray = baos.toByteArray();
}
catch (Exception e)
{
TraceDbLog.writeError("Problem in createByteArray", e);
}
return bArray;
}
Well the above code was written earlier for writing HashMap to BLOB i am using same for converting ArrayList if HashMap to BLOB.
The problem which is occurring in read code when i am reading the blob.
private Object readBytes (ResultSet rs, String columnName)
throws SQLException
{
ObjectInputStream ois = null;
byte [] newArray;
Object obj = null;
try
{
newArray = rs.getBytes(columnName);
ois = new ObjectInputStream (new ByteArrayInputStream(newArray));
obj = ois.readObject ();
}
In the read part the object is not coming as arrayList of hasMap and in debug perspective in eclipse eclipse is also not able to inspect the object which is coming.
I have also tried typecasting the object to List but still no success in getting the right response.
Please tell me whether there is any flaw in reading/writing the above BLOB.
I have added sample coding for convert ArrayList to byte[].
One reasonable way would be to use UTF-8 encoding like DataOutputStream does for each string in the list. For a string it writes 2 bytes for the length of the UTF-8 encoding followed by the UTF-8 bytes.
This would be portable if you're not using Java on the other end. Here's an example of encoding and decoding an ArrayList:
// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}
The easiest way is to convert it to json string and then to bytes
Gson gson = new Gson();
Type type = new TypeToken<List<Alarm>>() {}.getType();
String json = gson.toJson(list, type);
byte[] bytes = json.getBytes();

Serialization issues

public void writeObject(String outFile) {
try {
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student[] copy = this.getStudents();
for (Student st : copy){
oos.writeObject(st);}
oos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
The code above is the function I use to serialize the contents of my repository,getStudens() is returning an array of my data.
public void readSerialized(String fileName) throws Exception {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
while(fis.available()>0){
ctrl.addC((Student) ois.readObject());}
ois.close();
}
This my deserialization function which should recreate my data and add it again in my repository.The problem is that it doesn't recreate the data I had in my repository when I serialized it first.
What I had in repository before serialization:
1 a 4.0 6.0
2 b 10.0 10.0
3 c 2.0 2.0
4 d 8.0 2.0
5 e 6.0 2.0
What the deserialization returns:
0 3.0
0 5.0
Does this means that my serialization function isn't correct or something goes wrong when I deserialize?
Your code is needlessly complicated and using available() is always rather confusing I find. It means you can read without a system call it doesn't mean there is nothing left.
I suggest just serializing the array.
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.getStudents());
oos.close();
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Student[] copy = (Student[]) ois.readObject();
ois.close();
In Java, arrays are objects too.

Convert byte [] to ArrayList<Object>

I have a byte[] that i obtained using Object ArrayList<Obj>
Can anyone tell me how to convert my byte[] to Object ArrayList?
Coveting ArrayList like this:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
oos = new ObjectOutputStream(bos);
oos.writeObject(mArrayList);//mArrayList is the array to convert
byte[] buff = bos.toByteArray();
Now you've given us the information about how you did the conversion one way... you need:
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
try {
#SuppressWarnings("unchecked")
ArrayList<Object> list = (ArrayList<Object>) ois.readObject();
...
} finally {
ois.close();
}
I'm going to go with the obvious answer here...
for(byte b : bytearray) {
arraylist.add(new Byte(b));
}

send changed hashmap but get the same one using ObjectOutputStream and ObjectInputStream

public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 2345);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();
testMap.put(1,1);
oos.writeObject(testMap);
oos.flush();
testMap.put(2,2);
oos.writeObject(testMap);
oos.flush();
oos.close();
}
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(2345);
Socket s = ss.accept();
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println((HashMap<Integer, Integer>) ois.readObject());
System.out.println((HashMap<Integer, Integer>) ois.readObject());
ois.close;
}
The code above is from two files.
When running them, the console prints the same result:
{1=1}
{1=1}
How can this happen?
An ObjectOutputStream remembers the objects it has written already and on repeated writes will only output a pointer (and not the contents again). This preserves object identity and is necessary for cyclic graphs.
So what your stream contains is basically:
HashMap A with contents {1:1}
pointer: "HashMap A again"
You need to use a fresh HashMap instance in your case.
As Thilo already said, an ObjectOutputStream keeps a cache of things it has written already. You can either use a fresh map as he suggests, or clear the cache.
Calling ObjectOutputStream.reset between the calls to writeObject will clear the cache and give you the behavior you originally expected.
public static void main(String[] args) throws IOException,
ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
HashMap<Integer, Integer> foo = new HashMap<>();
foo.put(1, 1);
oos.writeObject(foo);
// oos.reset();
foo.put(2, 2);
oos.writeObject(foo);
}
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
System.out.println(ois.readObject());
System.out.println(ois.readObject());
}
}

Categories

Resources