by, 11-10-2011 at 05:08 PM (7173 Views)
We already know that we can serialize object of classes that implement serializable interface. Make a class that implements serializable interface, make an object of it and save it to disk. You may retrieve to confirm that the object has the required data or not. Vector class also implements serializable interface, so you can also store vectors on disk.
How about Arrays?
Arrays are of some type. Thing to note is which classes implement Serializable interface. Integer, Short, Float, Double, Long, String classes implement Serializable interface. So arrays of these types can be serialized.
Lets take an example:
;Java Code:int array = new int ; array = 10; array = 20; array = 30; array = 40; array = 50; int tmp_array = new int ; // writing array to disk FileOutputStream f_out = new FileOutputStream("C:\myarray.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (array); // reading array from disk FileInputStream f_in = new FileInputStream("C:\myarray.data"); ObjectInputStream obj_in = new ObjectInputStream (f_in); tmp_array = (int)obj_in.readObject(); for(int i=0;i<5;i++) System.out.println(tmp_array[i])
In the example above, we declared an integer array and inserted some data into it. Then that array was written to disk (serialized) on a file.
To make sure that the array was saved with data, we fetched the array from the same file using FileInputStream and ObjectInputStream. At the end, the fetched array is displayed on the console and now we are sure that we achieved what we wanted.
Similarly we can also searilize Integer, Short, Float, Double, Long, String.
Happy coding.Java Code:int a= 10; // writing int to disk FileOutputStream f_out = new FileOutputStream("C:\myint.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (a);